2

I know it's possible to call a method by its name like this:

 NSString *string =@"methodName";
[self performSelector:NSSelectorFromString(string)];

And that it will execute the method below:

-(void)methodName
   {
              // todo:.....
   }

I'm wondering how to call a method which has parameters like this:

-(void)methodName:(NSString *)_name :withValue (NSString *) value
     {
              // todo:.....
     }
rainydaymatt
  • 594
  • 3
  • 10
  • 21
Lochana Ragupathy
  • 4,320
  • 2
  • 25
  • 36

3 Answers3

2

You can use -performSelector:withObject:

NSDictionary *dic = @{@"name":@"stringName",@"value":@"12"};

NSString *string =@"methodName:";
[self performSelector:NSSelectorFromString(string) withObject:dic];

And in -methodName:

-(void) methodName:(id)obj
{
    NSDictionary *dic = (NSDictionary *)obj;
    [self methodName:dic[@"name"] withValue:dic[@"value"]];
}
onevcat
  • 4,591
  • 1
  • 25
  • 31
  • i cant directly pass the arguments to the method? – Lochana Ragupathy Dec 28 '12 at 05:00
  • Yes, it is impossible by performSelector, as I know. You can refer to [this answer](http://stackoverflow.com/questions/8439052/ios-how-to-implement-a-performselector-with-multiple-arguments-and-with-afterd) for some detail. Maybe you could try dispatch if you really want multiple parameters. – onevcat Dec 28 '12 at 05:06
  • i go with your answer and it worked for me and better to have a dictionary while passing the args with the help of key while coding dynamically thanks onevcat – Lochana Ragupathy Dec 28 '12 at 05:18
2

I don't know the exact syntax off the top of my head, but you can do this with NSInvocation.

Michael Mior
  • 28,107
  • 9
  • 89
  • 113
  • For who needs it an example here: http://stackoverflow.com/questions/11477951/comparing-two-strings-through-a-selector-unexpected-result , it also explains how to take the return value. – Ramy Al Zuhouri Dec 28 '12 at 05:10
0

Well I dont know what exactly is needed but from my understanding , it is something like :

NSArray *fruits = [NSArray arrayWithObjects:@"Apple", @"Mango", nil]; 
NSArray *drinks = [NSArray arrayWithObjects:@"Drink1", @"Drink2",nil];
[self serveOrdersWith:fruits andDrinks:drinks];

Somewhere in the class , the method will be called with the argument array fruits i.e.

-(NSArray*)serveOrdersWith :(NSArray*)array1 andDrinks:(NSArray*)array2{
     //Your code here but I will finish with this only
    NSArray *orderArray;
    [orderArray addObject:array1];
    [orderArray addObject:array2];
    return orderArray;
}
Zen
  • 3,047
  • 1
  • 20
  • 18