6

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

2
  • 5
    Alex'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. Commented Jan 5, 2010 at 10:05
  • Ya i agree with you.Can u tell me how to instantiate a object of other class/module? Commented Jan 5, 2010 at 10:09

2 Answers 2

13
MyClass *myClass = [[MyClass alloc] init];
OtherClass *otherClass = [[OtherClass alloc] init];
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply. I also wanted to know how to instantiate a object of other class/module?
I meant to state that other class is a other project and not the name of the class..Then what is the syntax?
I don't understand what you mean. I don't know how to instantiate a project.
12

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.