I'm trying to write a method in Objective C which takes a @selector as a parameter. It works fine - provided that I don't want the selector itself to have parameters (and I do).
- (void) testWithInput:(NSString*) testString1 andInput:(NSString*)testString2 {
NSLog(@"%@ %@", testString1, testString2);
}
- (void)executeSelector:(SEL)func fromObject:(id)object {
[object performSelector:func];
}
- (void)runSelector {
NSString* string1 = @"Hello ";
NSString* string2 = @"World";
[self executeSelector:@selector(testWithInput:andInput:) fromObject:self];
}
But how, in the runSelector function can I specify that string1 and string2 need to be passed in as arguments for the selector?
I suppose that I could pass in the parameters as a separate set of arguments to execute selector - but that feels quite messy. Is there a neater way?
I've done a bit of research, on StackOverflow (and elsewhere) - but either the answer isn't quite right or I can't understand it fully.
How to I pass @selector as a parameter?
How can I pass a parameter to a selector?
Objective-C: Calling selectors with multiple arguments
In fact, I'm comfortable passing parameters to selectors normally - it's when the selector is itself a parameter that I have a problem.
CodePudding user response:
You need to add parameters for the arguments. Your contrived example will work with the following changes:
- (void) testWithInput:(NSString*) testString1 andInput:(NSString*)testString2 {
NSLog(@"%@ %@", testString1, testString2);
}
- (void)executeSelector:(SEL)func fromObject:(id)object withString1:(NSString *)string1 andString2:(NSString *)string2 {
// This doesn't scale. Two arguments is as far as you can go using `performSelector`.
[object performSelector:func withObject:string1 withObject:string2];
}
- (void)runSelector {
NSString* string1 = @"Hello ";
NSString* string2 = @"World";
[self executeSelector:@selector(testWithInput:andInput:) fromObject:self withString1:string1 andString2:string2];
}
Since it's unclear what you are actually trying to accomplish it is difficult to offer any further advice on a better solution other than to suggest using blocks is likely a better choice.