Runtime class creation in iPhone
I need to split my job with my partner for designing game stages, and we badly need to use plist. So, say I have 20 different types of classes from which I need to dynamically instantiate objects in runtime. A particular class will be selected from plist inp开发者_StackOverflow社区ut and an object of the class will be created on the fly.
The first thing that went through my mind was switch()
and that was a bit dated I guess.
So I searched Stack Overflow and realized that iOS had NSClassFromString
and objc_getclass
.
- Create a class at runtime - Why do NSClassFromString AND objc_getclass return nil ?
- NSClassFromString returns nil
After few tries, I can tell NSClassFromString
is really nice since I can just say what class I want upfront in plist and bam! there we go. Setting object properties is done with KeyValue dictionary after that and it's all done like a magic.
My question is, how can I call class methods (those that start with +
) if you're to create objects this way? I've looked up documents and there is NSSelectorFromString()
. But isn't it for an instance rather than a class?
NSClassFromString
returns the class object not an instance of the class. Eg:
Class dateClass = NSClassFromString(@"NSDate"); //get the class object
NSDate *dateInstance = [dateClass date]; //call a class method on the class object
You can call performSelector:
on a class.
For example you can call:
[NSClassFromString(@"UIViewController") performSelector:NSSelectorFromString(@"setToolbarItems:")]
精彩评论