How to dynamically instantiate a class in Objective-C

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

+5
source share
2 answers
MyClass *myClass = [[MyClass alloc] init];
OtherClass *otherClass = [[OtherClass alloc] init];
+11
source

On iPhone, if you want to instantiate a class with the class name, you can use the objc_lookUpClass execution function.

For example, if I have a base class BaseHandler and you want to instantiate an object of the right subclass at runtime (hardcoded 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];
+12
source

All Articles