开发者

Instantiate an arbitrary class in Objective C

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 ar开发者_如何学Goray without hard-coding each of the possible classes inside a massive if-else test?


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];


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.


Yes, I guess memset() will be of help

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜