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

杀马特。学长 韩版系。学妹 提交于 2019-12-10 18:12:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!