My function looks like this
-(void) doTransition:(id)sender withID:(int) n
How do I pass int n to selector,
target:self selector:@selector(doTransition:)withID:3
this won't work
Please help Thanks
My function looks like this
-(void) doTransition:(id)sender withID:(int) n
How do I pass int n to selector,
target:self selector:@selector(doTransition:)withID:3
this won't work
Please help Thanks
So, I Googled "calling selectors with arguments" and got a bunch of results, the first of which is a question here on SO: Objective-C: Calling selectors with multiple arguments
The most voted answer there has some details, specifically:
[selectorTarget performSelector:mySelector withObject:@3];
This is a simple task to perform. More information can be found at the linked question/answer area.
Notice the @3
I passed, which is not an int
but an NSNumber
. If you have an int
value you can easily get an NSNumber
by performing [NSNumber numberWithInt:myIntValue]
. The @3
is shorthand syntax available in clang 3.4 for creating an NSNumber
with an integer value. The use of NSNumber
here instead of int
is important because this selector call expects an id
type as the withObject:
parameter and so thus I need an object, and not a primitive type (whether the compiler auto-wraps for you, I can't say).
Another important note is that there are three performSelector:
functions defined:
- (id)performSelector:(SEL)aSelector;
- (id)performSelector:(SEL)aSelector withObject:(id)anObject;
- (id)performSelector:(SEL)aSelector withObject:(id)anObject withObject:(id)anotherObject;
So you can see you can use functions that don't take values and functions that take one or two values as selectors but outside of that you'd most likely need to write your own logic for calling functions with greater than 2 arity.
The short answer is that you don't. methods like performSelector: are set up to pass NSObjects as parameters, not scalar values.
There is a method performSelector:withObject:withObject: that will invoke a method with 2 object parameters.
You can trigger a method with any type of parameters by creating an NSInvocation, but it's a fair amount of work, and a little tricky to figure out how to do it.
In your case it would be simpler to refactor your method to take the ID parameter as an NSNumber object.
It not easy to use NSNumber to pass value, I implemented a method to pass an object as int.
+ (void)showNotice:(NSString *)str atView:(UIView *)view delay:(int)delay {
[cc_message cc_instance:CC_Notice.shared method:@selector(showNotice:atView:delay:) params:str,view,Int(delay)];
}
And use invocation to receive and reduction to int.
CC_Int *ccint = (CC_Int *)obj;
int value = ccint.value;
[invocation setArgument:&value atIndex:i+2];
You need to pass a NSDictionary with the values you want to send, something like:
NSDictionary *myDictionary = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:3] forKey:@"myInt"];