Can I know how to dynamically instantiate a class in Objective-C?
-
5Alex's answer is correct, but for the avoidance of all doubt, your question isn't quite right. You do not instantiate a class. You instantiate an object. An object is an instance of a class.Graza– Graza2010-01-05 10:05:45 +00:00Commented Jan 5, 2010 at 10:05
-
Ya i agree with you.Can u tell me how to instantiate a object of other class/module?suse– suse2010-01-05 10:09:23 +00:00Commented Jan 5, 2010 at 10:09
Add a comment
|
2 Answers
MyClass *myClass = [[MyClass alloc] init];
OtherClass *otherClass = [[OtherClass alloc] init];
3 Comments
suse
Thanks for the reply. I also wanted to know how to instantiate a object of other class/module?
suse
I meant to state that other class is a other project and not the name of the class..Then what is the syntax?
Alex Reynolds
I don't understand what you mean. I don't know how to instantiate a project.
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];