Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to selector in Objective-C

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

like image 777
user2735868 Avatar asked Nov 11 '13 15:11

user2735868


2 Answers

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.

like image 111
Brandon Buck Avatar answered Oct 26 '22 06:10

Brandon Buck


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.

like image 20
Duncan C Avatar answered Oct 26 '22 07:10

Duncan C