Objective C create object by class

13,547

Solution 1

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

Solution 2

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.

Share:
13,547
Richard J. Ross III
Author by

Richard J. Ross III

I am Richard J. Ross III, and am an experienced iOS, android, and .NET programmer, having written apps, open-source libraries, and tools.

Updated on July 23, 2022

Comments

  • Richard J. Ross III
    Richard J. Ross III almost 2 years

    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.