Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@selector - With Multiple Arguments?

Tags:

objective-c

I have been using @selector today for the first time and have not been able to work out how to do the following? How would you write the @selector if you had more than one argument?

No arguments:

-(void)printText {
    NSLog(@"Fish");
}

[self performSelector:@selector(printText) withObject:nil afterDelay:0.25];

Single argument:

-(void)printText:(NSString *)myText {
    NSLog(@"Text = %@", myText);
}

[self performSelector:@selector(printText:) withObject:@"Cake" afterDelay:0.25];

Two arguments:

-(void)printText:(NSString *)myText andMore:(NSString *)extraText {
    NSLog(@"Text = %@ and %@", myText, extraText);
}

[self performSelector:@selector(printText:andMore:) withObject:@"Cake" withObject:@"Chips"];

Multiple Arguments: (i.e. more than 2)

NSInvocation

like image 602
fuzzygoat Avatar asked Feb 19 '10 15:02

fuzzygoat


2 Answers

 

 - (id)performSelector:(SEL)aSelector
           withObject:(id)anObject  
           withObject:(id)anotherObject

From the Documentation:

This method is the same as performSelector: except that you can supply two arguments for aSelector. aSelector should identify a method that can take two arguments of type id. For methods with other argument types and return values, use NSInvocation.

so in your case you would use:

[self performSelector:@selector(printText:andMore:)
           withObject:@"Cake"
           withObject:@"More Cake"]
like image 96
cobbal Avatar answered Nov 18 '22 17:11

cobbal


As an alternative for NSInvocation when you have more than two parameters, you can use NSObject's -methodForSelector: as in the following example:

SEL a_selector = ...
Type1 obj1 = ...
Type2 obj2 = ...
Type3 obj3 = ...
typedef void (*MethodType)(id, SEL, Type1, Type2, Type3);
MethodType methodToCall;
methodToCall = (MethodType)[target methodForSelector:a_selector];
methodToCall(target, a_selector, obj1, obj_of_type2, obj_of_type3);
like image 19
Yoav Avatar answered Nov 18 '22 18:11

Yoav