Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C create object by class

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.

like image 615
Richard J. Ross III Avatar asked Sep 07 '10 18:09

Richard J. Ross III


People also ask

What is difference between a class and an object?

Class is a logical entity whereas objects are physical entities. A class is declared only once. On the other hand, we can create multiple objects of a class.


2 Answers

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

like image 52
cobbal Avatar answered Sep 19 '22 18:09

cobbal


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.

like image 36
Greg Sexton Avatar answered Sep 17 '22 18:09

Greg Sexton