Answers:
NSClassFromString()冒着混淆类名或以其他方式使用不存在的类的风险。如果您犯了该错误,直到运行时您都不会发现。相反,如果您使用内置的Objective-C类型Class创建变量,则编译器将验证该类是否存在。
例如,在您的.h:
@property Class NameOfClass;
然后在您的.m:
id object = [[NameOfClass alloc] init];
如果您输错了类名或它不存在,则在编译时会出现错误。我也认为这是更干净的代码。
如果您正在使用Objective-C的工作没有NeXTstep(OS X,iOS,GNUstep等)的系统,或者你只是觉得这个方法更清洁,那么你可以利用Objective-C语言运行时库的API。下Objective-C 2.0:
#import <objc/runtime.h>
//Declaration in the above named file
id objc_getClass(const char* name);
//Usage
id c = objc_getClass("Object");
[ [ c alloc ] free ];
在Objective-C(1.0或未命名的版本)下,您将使用以下内容:
#import <objc/objc-api.h>
//Declaration within the above named file
Class objc_get_class( const char* name);
//Usage
Class cls = objc_get_class( "Test" );
id obj = class_create_instance( cls );
[ obj free ];
我尚未测试1.0版本,但是我已经2.0在生产中的代码中使用了该功能。我个人认为利用该2.0功能是清洁如果有比NS功能,因为它消耗更少的空间:the length of the name in bytes + 1 ( null terminator )对于2.0 API相比the sum of two pointers (isa, cstring),一size_t length (cstring_length),和length of the string in bytes + 1对NeXTSTEPAPI。