开发者

How to dynamically instantiate a class in Objective-C

开发者 https://www.devze.com 2022-12-15 23:21 出处:网络
Can I know how to dynamically instantiate a class in Object开发者_StackOverflow中文版ive-C?MyClass *myClass = [[MyClass alloc] init];

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

精彩评论

暂无评论...
验证码 换一张
取 消