Objective C calling method dynamically with a string

IphoneObjective CDynamicMethodsMessaging

Iphone Problem Overview


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

Iphone Solutions


Solution 1 - Iphone

You can try something like

SEL s = NSSelectorFromString(selectorName);
[anObject performSelector:s];

Solution 2 - Iphone

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIPadHackAndSlashView Question on Stackoverflow
Solution 1 - IphoneshreyasvaView Answer on Stackoverflow
Solution 2 - IphoneAdam MilliganView Answer on Stackoverflow