是否可以使用变量动态更改代码中 class 的名称?

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

我有这个功能:

- (NSString*) getId:(id)id_field withColumn:(int)test_column withTable:(NSString *) tableName  //renvoyer le label
{
    NSError *error = nil;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:tableName
                                              inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    for (<tableName of class> *info in fetchedObjects)
    {
        if (test_column == LBL2_CLMN)
        {
            NSLog(@"info.id :%@", info.id);
            if ([info.id compare:id_field] == NSOrderedSame)
                NSLog(@"info.id :%@", info.label1);
            return info.label1;
        }
        else if (test_column == LBL1_CLMN)
        {
            if ([info.id compare:id_field] == NSOrderedSame)
                return info.label2;
        }
    }
    return @"";
}

如何使用变量 tableName 更改 class 的名称以实例化 *info?

可能吗?

不是直接的,而是因为 executeFetchRequest returns NSManagedObject 在重复循环中使用它并将对象转换为 if - else 中预期的 class范围。

NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *object in fetchedObjects)
{
    if (test_column == LBL2_CLMN)
    {
        ClassA *info = (ClassA *)object;
        NSLog(@"info.id :%@", info.id);
        if ([info.id compare:id_field] == NSOrderedSame) {
            NSLog(@"info.id :%@", info.label1);
            return info.label1;
        }
    }
    else if (test_column == LBL1_CLMN)
    {
        ClassB *info = (ClassB *)object;         
        if ([info.id compare:id_field] == NSOrderedSame)
            return info.label2;
    }
}
return @"";

而且我猜第二个 if 子句中缺少一对大括号。

你必须使用 NSClassFromString 方法,然后使用 id 关键字来获取对象:

NSError *error = nil;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:table inManagedObjectContext:managedObjectContext];

[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

Class theClass = NSClassFromString(table);
id info = [theClass new];

for (info in fetchedObjects)
{
   .....
}

return @"";