Can I know how to dynamically instantiate a class in Objective-C?
我可以知道如何在Objective-C中动态实例化一个类吗?
2 个解决方案
#1
11
MyClass *myClass = [[MyClass alloc] init];
OtherClass *otherClass = [[OtherClass alloc] init];
#2
12
On the iPhone, if you want to create an instance of a class given the class name you can use the runtime function objc_lookUpClass.
在iPhone上,如果要创建给定类名的类的实例,可以使用运行时函数objc_lookUpClass。
For example, if I have a base class BaseHandler and want to instantiate an object of the right subclass at runtime (hard coded as MyHandler in this example):
例如,如果我有一个基类BaseHandler并且想要在运行时实例化一个右子类的对象(在本例中硬编码为MyHandler):
#import <objc/objc.h>
[...]
NSString *handlerClassName = @"MyHandler"
id handlerClass = objc_lookUpClass([handlerClassName
cStringUsingEncoding:[NSString defaultCStringEncoding]]);
BaseHandler *handler = (BaseHandler *) [[handlerClass alloc] init];
#1
11
MyClass *myClass = [[MyClass alloc] init];
OtherClass *otherClass = [[OtherClass alloc] init];
#2
12
On the iPhone, if you want to create an instance of a class given the class name you can use the runtime function objc_lookUpClass.
在iPhone上,如果要创建给定类名的类的实例,可以使用运行时函数objc_lookUpClass。
For example, if I have a base class BaseHandler and want to instantiate an object of the right subclass at runtime (hard coded as MyHandler in this example):
例如,如果我有一个基类BaseHandler并且想要在运行时实例化一个右子类的对象(在本例中硬编码为MyHandler):
#import <objc/objc.h>
[...]
NSString *handlerClassName = @"MyHandler"
id handlerClass = objc_lookUpClass([handlerClassName
cStringUsingEncoding:[NSString defaultCStringEncoding]]);
BaseHandler *handler = (BaseHandler *) [[handlerClass alloc] init];