2

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 input 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.

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?

Community
  • 1
  • 1
Xylopia
  • 55
  • 6

2 Answers2

5

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
Benedict Cohen
  • 11,912
  • 7
  • 55
  • 67
  • The issue is I receive an instance as "id", which is fine but that generates warnings. This really explains. "NSClassFromString returns the class object not an instance of the class." Thank you very much! – Xylopia Feb 11 '11 at 10:26
  • I choose Ludovic's. His answer was what I was looking for. – Xylopia Feb 12 '11 at 10:01
2

You can call performSelector: on a class.

For example you can call:

[NSClassFromString(@"UIViewController") performSelector:NSSelectorFromString(@"setToolbarItems:")]
Ludovic Landry
  • 11,606
  • 10
  • 48
  • 80