是否可以用字符串实例化一个类?

时间:2016-04-12 18:11:45

标签: objective-c class instance

我有50个类,名称如:table_address,table_name,table_lastname等...

而不是:

table_address *table;
table =[[table alloc] init];
id_to_send = table.id;

table_name *table;
table =[[table alloc] init];
id_to_send = table.id;

table_lastname *table;
table =[[table alloc] init];
id_to_send = table.id;

等...

有没有办法只有一个循环可以声明表并实例化它们以从每个表中提取id。我希望我没有被迫写100次......

例如:

for (first table to last table)
{
    table_xxxxxxx *table;
    table =[[table alloc] init];
    id_to_send = table.id;
}

由于

2 个答案:

答案 0 :(得分:0)

您可以使用NSClassFromString动态创建类。它会创建与您提供的名称相对应的类引用

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/#//apple_ref/c/func/NSClassFromString

假设它们都从包含属性id的类继承,您可以执行类似下面的操作

NSArray * classSuffixes = @[@"suffix1", @"suffix2", @"suffix100"];
for(NSString * suffix in classSuffixes) {
    NSString *tableIdentifier;

    NSString *className = [NSString stringWithFormat:@"table_%@",suffix];
    Class objectClass = NSClassFromString(className);
    CommonParentClass *table = (CommonParentClass *)[[objectClass alloc] init];
    tableIdentifier = table.id;
    // ....
}

对于NSManagedObject,您可以执行以下操作:

    NSArray * classSuffixes = @[@"suffix1", @"suffix2", @"suffix100"];
    for(NSString * suffix in classSuffixes) {
        NSString *tableIdentifier;

        NSString *className = [NSString stringWithFormat:@"table_%@",suffix];
        Class objectClass = NSClassFromString(className);
        NSManagedObject *table = [[objectClass alloc] init];
        NSArray *availableKeys = [[table.entity attributesByName] allKeys];
        if ([availableKeys containsObject:@"id"]) {
            tableIdentifier = [table valueForKey:@"id"];
        }
    }

答案 1 :(得分:0)

修改: 最后有一个解决方案。 我找到了解决方案。你可以在这里找到它:D

=> Is it possible to change dynamically the name of the class in the code with a variable?