views:

97

answers:

2

I would like to know how to create an object of the specified Class in objective c. Is there some method I am missing in the runtime docs? If so what is it? I would like to be able to do something like the following:

NSDictionary *types;

-(id<AProtocol>) createInstance:(NSString *) name
{
    if ((Class cls = [types objectForKey:name]) != nil)
    {
       return new Instance of cls;
    }
    else
    {
        [NSException raise:@"class not found" format:@"The specified class (%@) was not found.", name];
    }
}

please note that name is not a name of the class, but an abbreviation for it, and I cannot do what is indicated in Create object from NSString of class name in Objective-C.

+4  A: 

A simple [[cls alloc] init] will do the trick.

cobbal
+2  A: 

As cobbal has mentioned [[cls alloc] init] is usual practice. The alloc is a static class method, defined in NSObject, that allocates the memory and init is the instance constructor. Many classes provide convenience constructors that do this in one step for you. An example is:

NSString* str = [NSString stringWithString:@"Blah..."];

Note the * after NSString. You're working essentially with C here so pointers to objects!

Also, don't forget to free memory allocated using alloc with a corresponding [instance release]. You do not need to free the memory created with a convenience constructor as that is autoreleased for you. When you return your new instance of cls, you should add it to the autorelease pool so that you don't leak memory:

return [[[cls alloc] init] autorelease];

Hope this helps.

Greg Sexton
+1 for good point about autorelease.
Richard J. Ross III