是否可以用字符串实例化 class ?

Is it possible to instantiate a class with a string?

我有 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;

等...

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

例如:

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

谢谢

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

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

假设它们都继承自包含 属性 id 的 class,您可以执行如下操作

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"];
        }
    }

编辑: 终于有解决办法了。 我找到了解决方案。你可以在这里找到它:D

=>