Can I know how to dynamically instantiate a class in Objective-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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With