是否有可能dynamic改变代码中的类的名称与variables?

我有这个function:

- (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 @""; } 

我怎样才能改变class级的名字 为instanciate *信息与variablestableName?

可能吗 ?

您必须使用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 @""; 

不是直接的,但是因为executeFetchRequest返回NSManagedObject ,所以在重复循环中使用它,并将对象executeFetchRequestif - else范围中的期望类。

 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子句中缺less一对大括号。