如何在Objective-C中从字符串实例化类的对象?

时间:2022-09-24 23:12:02

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

我有一个字符串,它的值是必须实例化的类[MyClass]的名称,而MyClass有一个名为

 -(void)FunctionInClass;

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

我正在使用名为NSClassFromString的方法来实例化MyClass。我想知道

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?

我该怎么办,我是在Objective-C for iPhone app中做的?

1 个解决方案

#1


51  

1) what does NSClassFromString return??

1)NSClassFromString返回什么?

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

它返回一个Class,这意味着你可以[[NSClassFromString(@“MyClass”)alloc] init];有关详细信息,请参阅Mac Dev Center Docs。

2) what is id?

2)什么是id?

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

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

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

3)如何调用方法 - (void)使用实例在MyClass中的FunctioninClass。

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

#1


51  

1) what does NSClassFromString return??

1)NSClassFromString返回什么?

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

它返回一个Class,这意味着你可以[[NSClassFromString(@“MyClass”)alloc] init];有关详细信息,请参阅Mac Dev Center Docs。

2) what is id?

2)什么是id?

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

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

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

3)如何调用方法 - (void)使用实例在MyClass中的FunctioninClass。

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