Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call class method from NSString in obj-c?

In obj-c, how can I call

[myClass myString];

where myString = @"myMethod";

Which should be the equivalent of [myClass myMethod];

Not sure if this kind of meta language manipulation is possible.

like image 222
Tudor Avatar asked Jun 07 '11 10:06

Tudor


2 Answers

[myClass performSelector: NSSelectorFromString(myString)];

Docs:

  • -performSelector: sends the selector specified to the receiver
  • NSSelectorFromString() converts an NSString into a selector (type SEL)
like image 127
JeremyP Avatar answered Nov 10 '22 18:11

JeremyP


[myClass class] returns the metaclass, class methods are called on the metaclass. E.g.

[NSString someClassMethod];

NSString *instanceOfString = @"some string instance";
[[instanceOfString class] someClassMethod];

EDIT: I misread the question. Use NSSelectorFromString to get a SEL from an NSString. That's documented in Apple's Foundation Functions Reference where you'll also see NSClassFromString, NSStringFromClass, NSStringFromSelector, NSStringFromProtocol and NSProtocolFromString amongst others.

like image 20
Tommy Avatar answered Nov 10 '22 19:11

Tommy