Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically instantiate a class in Objective-C

Can I know how to dynamically instantiate a class in Objective-C?

like image 804
suse Avatar asked Jan 05 '10 10:01

suse


2 Answers

MyClass *myClass = [[MyClass alloc] init];
OtherClass *otherClass = [[OtherClass alloc] init];
like image 62
Alex Reynolds Avatar answered Nov 01 '22 02:11

Alex Reynolds


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];
like image 39
Rolf Staflin Avatar answered Nov 01 '22 01:11

Rolf Staflin