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.
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.
A simple [[cls alloc] init]
will do the trick.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With