how to instantiate an object of class from string in Objective-C?

空扰寡人 提交于 2019-12-28 13:40:53

问题


I've a String who's value is the name of the Class[MyClass] which has to be instantiated, and MyClass has a method called

 -(void)FunctionInClass;

i'm using the method called NSClassFromString to instantiate MyClass.I want to know

1) what does NSClassFromString return?? 
2) what is id? 
3) How to call method -(void)FunctioninClass which is in MyClass using the instance.

how should i proceed , i'm doing it in Objective-C for iPhone app?


回答1:


1) what does NSClassFromString return??

It returns a Class, which means you can do [[NSClassFromString(@"MyClass") alloc] init]; see Mac Dev Center Docs for more info.

2) what is id?

See http://www.otierney.net/objective-c.html#idtype

3) How to call method -(void)FunctioninClass which is in MyClass using the instance.

id myclass = [[NSClassFromString(@"MyClass") alloc] init];
[myclass FunctioninClass];



回答2:


NSClassFromString() is a function that returns an Objective-C class. That is, in Objective-C a class is an honourable object. An instance of the "Class" class...

And what is an Objective-C class good for?

for instantiating objects (via alloc init ) for introspection and reflection - to query it for the methods and properties instances of that class are exposed to the user for archiving/de-archiving instances of that class, and... to be able to run class methods (methods that do not require any specific instance of that class.

your last lines actually create an instance of the class whose name is the string passed to NSClassFromString.



来源:https://stackoverflow.com/questions/2226611/how-to-instantiate-an-object-of-class-from-string-in-objective-c

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