Can I know how to dynamically instantiate a class in Object开发者_StackOverflow中文版ive-C?
MyClass *myClass = [[MyClass alloc] init];
OtherClass *otherClass = [[OtherClass alloc] init];
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.
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):
#import <objc/objc.h>
[...]
NSString *handlerClassName = @"MyHandler"
id handlerClass = objc_lookUpClass([handlerClassName
cStringUsingEncoding:[NSString defaultCStringEncoding]]);
BaseHandler *handler = (BaseHandler *) [[handlerClass alloc] init];
精彩评论