C语言 在Objective-C中从类名的NSString创建对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2951828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create object from NSString of class name in Objective-C
提问by Sveinn Fannar
I was wondering if i could create a object of some class if i have the name of the class in a NSString. I know this is possible in other languages like ActionScript, C# and PHP...
我想知道如果我在 NSString 中有类的名称,我是否可以创建某个类的对象。我知道这在 ActionScript、C# 和 PHP 等其他语言中是可能的...
Something like this:
像这样的东西:
NSString *className = @"AwesomeViewController";
UIViewController *object = [[className alloc] initWithNibName:className bundle:nil];
回答by kennytm
Classes are first-class objects in Objective-C too. You can get the class object from an NSString with the NSClassFromString function.
类也是 Objective-C 中的一流对象。您可以使用NSClassFromString 函数从 NSString 获取类对象。
[[NSClassFromString(className) alloc] init...]

