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

问题描述 投票:23回答:2

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

 -(void)FunctionInClass;

我正在使用名为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.

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

objective-c instantiation
2个回答
52
投票

1) what does NSClassFromString return??

它返回一个类,这意味着你可以做[[NSClassFromString(@"MyClass") alloc] init];查看Mac Dev Center Docs获取更多信息。

2) what is id?

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

0
投票

NSClassFromString()是一个返回Objective-C类的函数。也就是说,在Objective-C中,一个类是一个光荣的对象。 “类”类的一个实例......

什么是Objective-C类有用?

用于实例化对象(通过alloc init)进行内省和反射 - 查询它以获取该类的方法和属性实例,以便向用户公开该类的归档/解压缩实例,以及...以便能够运行类方法(不需要该类的任何特定实例的方法。

您的最后一行实际上创建了一个类的实例,其名称是传递给NSClassFromString的字符串。

© www.soinside.com 2019 - 2024. All rights reserved.