objective c dynamic object creation

坚强是说给别人听的谎言 提交于 2019-12-03 14:02:33

问题


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 string, but I doubt it is that easy in Objective c.

NSString * className;
id theObject;
className = @"TestObject";
theObject = [[className alloc] init];

here is a break down of what it might look like. I want to try and avoid using a giant case style statement.

Is it possible to use the selector system for this?

any ideas?

Cheers


回答1:


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];



回答2:


You can get a Class object dynamically with NSClassFromString()

Class c = NSClassFromString(@"ClassName");
id obj = [[c alloc] init];


来源:https://stackoverflow.com/questions/2175547/objective-c-dynamic-object-creation

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