76

Im just wondering whether there is a way to call a method where i build the name of the method on the fly with a string.

e.g. I have a method called loaddata

-(void)loadData;

to call this i would normally call it like

[self loadData];

But i want to be able to call it dynamically with a string e.g.

NSString *methodName = [[NSString alloc] initWithString:@"loadData"];
[self methodName];

This is a stupid example but i hope you get my point. I am using it for databinding classes that I am setting up for my IPad application. Hard to explain but to get it to fire I need to work out how to call a method with a string.

Any ideas?

Thanks

2
  • 1
    +1 for clear, simple question! Commented Dec 15, 2010 at 5:12
  • The method I want to call is a function that returns an NSString. Commented Dec 15, 2010 at 5:23

2 Answers 2

110

You can try something like

SEL s = NSSelectorFromString(selectorName);
[anObject performSelector:s];
Sign up to request clarification or add additional context in comments.

5 Comments

In this situation the method returns a value which is an NSString in one case. I get an error saying Lvalue required as left operand of assignment. This is my code: SEL s = NSSelectorFromString(@"getIDString"); [self text] = [boundEntity performSelector:s];
what is [self text],where you assign the value return getIDString.
[boundEntity performSelector:s] returns a value of type that does not match the type of [self text]. I think you need to set @property for text and call [self setText:[[boundEntity performSelector:s]]].
performSelector may cause a leak because selector is unknown!
13

You can use the objc_msgSend function. It takes two parameters, the receiver and the selector to send to it:

objc_msgSend(self, someSelector);

You'll need to turn your string into the appropriate selector using NSSelectorFromString:

NSString *message = [self getSomeSelectorName];
objc_msgSend(self, message);

The method also takes a variable number of arguments, so you can send messages with any number of arguments.

NSString *message = [self getSomeSelectorNameWithManyArguments];
objc_msgSend(self, message, arg1, arg2, arg3, arg4);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.