Unis
Unis

Reputation: 377

Dynamically instantiating object Objective-C

In Java we can instantiate an object (knowing only the parameters types) dynamically like this:

Class<?> msgClass = Class.forName(className);
constructor = msgClass.getConstructor(String.class, String.class, String.class);    
MyClass myClass = (MyClass) constructor.newInstance(myString, myString2, myString3);    

    public class MyClass {        
        public MyClass(String s, String s2, String s2){}
    }

Is there a way to do the same in objective-c, knowing only the parameters types to be passed in to the objective-c class constructor.

Thanks in advance.

Upvotes: 4

Views: 1492

Answers (1)

Ben Zotto
Ben Zotto

Reputation: 70998

Yes, depending on what you're really doing. ObjC doesn't have language-level "constructors" in the same way-- there are init methods which usually called alongside the alloc instantiation method, but note that init is there by framework convention and not by spec, so the runtime doesn't "know" what "constructor" you'd want to call.

You can instantiate an object (the equivalent of allocating it) like this:

id myObj = class_createInstance(NSClassFromString(@"MyClass"));

although you might as well do it more directly:

id myObj = [NSClassFromString(@"MyClass") alloc];

But then you'd still need to call whatever init method you want on it. If you don't want to do this directly, you need to know the selector for the method so you can send the object the correct message. The selector is a static representation of the message signature. You could invoke that method through the runtime API like this:

myObj = objc_msgSend(myObj, @selector(initWithStr1:str2:str3), myString1, myString2, myString3);
// Check myObj for nil which means a failed init.

ObjC runtime reference: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html

Upvotes: 7

Related Questions