Tudor
Tudor

Reputation: 4174

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.

Upvotes: 6

Views: 4371

Answers (5)

Sherm Pendley
Sherm Pendley

Reputation: 13622

Alternatively, in case you need more flexibility in argument and/or return types than performSelector: and friends will give you, have a look at the NSInvocation class.

Upvotes: 0

JeremyP
JeremyP

Reputation: 86691

[myClass performSelector: NSSelectorFromString(myString)];

Docs:

Upvotes: 10

Tommy
Tommy

Reputation: 100652

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

Upvotes: 1

cem
cem

Reputation: 3321

SEL mySelector = NSSelectorFromString(@"myMethod");
[myClass performSelector:mySelector];

Upvotes: 0

Tom Jefferys
Tom Jefferys

Reputation: 13310

You can use NSSelectorFromString, something along the lines of the following should work:

 SEL selector = NSSelectorFromString(@"myMethod");
 [myClass performSelector:selector withObject:nil];

Upvotes: 1

Related Questions