objective c dynamic object creation

前端 未结 2 560
长情又很酷
长情又很酷 2021-02-06 18:35

Quick question for you. I want to be able to create an instance of an object. The object type is based of a string.

In php you can just replace the class name with a s

相关标签:
2条回答
  • 2021-02-06 18:40

    You can get a Class object dynamically with NSClassFromString()

    Class c = NSClassFromString(@"ClassName");
    id obj = [[c alloc] init];
    
    0 讨论(0)
  • 2021-02-06 19:03

    You can get a class by its name using one of the following obj-c runtime functions (you may need to import header:

    id objc_lookUpClass(const char *name)
    id objc_getClass(const char *name)
    

    So your code may look like (have not tested it though):

    NSString * className = @"TestObject";
    id theObject = nil;
    Class myClass = objc_lookUpClass([className UTF8String]);
    if (myClass)
       theObject = [[myClass alloc] init];
    
    0 讨论(0)
提交回复
热议问题