Claudio Claudio - 2 years ago 66
iOS Question

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

I have this 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 @"";
}


How can I change the name of the class for instanciate *info with the variable tableName ?

Is it possible ?

Answer Source

You have to use the NSClassFromString method and then use id keyword to get the object:

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 @"";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download