tags:

views:

187

answers:

3

I have an NSMutableArray of objects in Objective C. I'm filling this up based on the contents of a data file, which contains the class each element should be and a list of parameters. All of the possible classes inherit from a common parent class.

Is there any way of instantiating each element of the array without hard-coding each of the possible classes inside a massive if-else test?

A: 

Yes, I guess memset() will be of help

Sachin Chourasiya
+7  A: 

You currently store the name of the class in the data file as well as the object's parameters.

You can therefore use NSClassFromString to instantiate that custom class object and initialize its state:

NSString *_myCustomClass = // get custom class name from data file...
id _myCustomObject = [[NSClassFromString(_myCustomClass) alloc] init];
// set up _myCustomObject's state from data file's parameters...
[_myMutableArray addObject:_myCustomObject];
[_myCustomObject release];
Alex Reynolds
+1 spot on answer. Is it worth mentioning how you'd get the selector for a particular property (by name?) in order to set its value?
Rob Fonseca-Ensor
@Rob - if the properties were declared using `@property`, then the simplest answer would be to use `setValue:forKey:`.
Dave DeLong
Even if the properties were not declared using `@property`, you can still use `setValue:forKey:` Key-Value coding predated Objective-C 2.0's `@property` declarations and searches for appropriately named setter(s) followed by direct ivar assignment.
Barry Wark
A: 

If you're in control of writing that data file too, you might find it easier to just use standard objective C archiving (called serialization in other languages). It's an easy way to write and read objects into and from a file.

Rob Fonseca-Ensor