Object C creates an object by class

I would like to know how to create an object of the specified Class in an object c. Is there some method missing from the runtime docs? If so, then 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]; } } 

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

+7
initialization class objective-c
source share
2 answers

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

+18
source share

As cobbal [[cls alloc] init] noted, this is common practice. alloc is a static class method defined in NSObject that allocates memory, and init is an instance constructor. Many classes provide convenience constructors that do this in one step for you. Example:

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

Note * after NSString . You mainly work with C here, so pointers to objects!

Also, do not forget to free the allocated memory using alloc with the corresponding [instance release] . You do not need to free up memory created using the convenience constructor, as this is auto-implemented for you. When you return your new cls instance, you should add it to the autodetection pool so that there is no memory leak:

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

Hope this helps.

+3
source share

All Articles