问题
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 ?
回答1:
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 @"";
回答2:
Not directly, but since executeFetchRequest
returns NSManagedObject
use that in the repeat loop and cast the object to the expected class in the if - else
scopes.
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 @"";
And I guess that there is a pair of braces missing in the second if
clause.
来源:https://stackoverflow.com/questions/36579112/is-it-possible-to-change-dynamically-the-name-of-the-class-in-the-code-with-a-va