Objective-C method call dynamically using string

I'm just wondering if there is a way to call a method when I build the method name on the fly with a string.

eg. I have a loaddata method p>

-(void)loadData; 

to call it, I usually call it like

 [self loadData]; 

But I want to be able to dynamically call it with a string, for example.

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

This is a stupid example, but I hope you understand my point. I use it for the data binding classes that I configure for my iPad application. It's hard to explain, but in order to run it, I need to figure out how to call the method with a string.

Any ideas?

thank

+69
methods dynamic objective-c iphone messaging
Dec 15 '10 at 5:05
source share
3 answers

You can try something like

 SEL s = NSSelectorFromString(selectorName); [anObject performSelector:s]; 
+99
Dec 15 '10 at 5:12
source share
— -

You can use the objc_msgSend function. To send it, two parameters are required: receiver and selector:

 objc_msgSend(self, someSelector); 

You will need to turn the string into the corresponding selector using NSSelectorFromString :

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

The method also accepts 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); 
+11
Dec 15 '10 at 5:16
source share
+7
Dec 15 '10 at 5:09 a.m.
source share



All Articles