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

In obj-c, what can I call

[myClass myString];

Where myString = @"myMethod";

What should be the equivalent [myClass myMethod];

Not sure if this kind of metalanguage is possible.

+5
source share
5 answers

[myClass class]returns a metaclass, class methods are called in a metaclass. For instance.

[NSString someClassMethod];

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

EDIT: I misunderstood the question. Use NSSelectorFromStringto get SEL from NSString. This is described in the Apple Guide basic functions , where you will also see NSClassFromString, NSStringFromClass, NSStringFromSelector, NSStringFromProtocoland NSProtocolFromString, among others.

+1
source
[myClass performSelector: NSSelectorFromString(myString)];

Documents:

+9

You can use NSSelectorFromStringsomething in the lines of the following should work:

 SEL selector = NSSelectorFromString(@"myMethod");
 [myClass performSelector:selector withObject:nil];
+1
source
SEL mySelector = NSSelectorFromString(@"myMethod");
[myClass performSelector:mySelector];
0
source

Alternatively, if you need more flexibility in the arguments and / or return types than performSelector:and friends will give you, take a look at NSInvocation .

0
source

All Articles