Selector function with int parameter?
Using Cocos2d-iphone, and objective-c game development framework.
I create a button with:
CCMenuItemImage *slot = [CCMenuItemImage itemFromNormalImage:@"BattleMoveSelectionSlot1.png"
selectedImage:@"BattleMoveSelectionSlot2.png"
target:self selector:@selector(moveChosen:i)];
And my moveChosen
method is:
-(void)moveChosen:(int)index {
}
However, for some reason I get an error on @selector(moveChosen:i)
where i is an integer. How, then开发者_JAVA百科, may I pass an integer parameter to my function when the button is pressed?
The error is
Expected ':'
Georg is correct. Note that as implemented, this will invoke undefined behaviour since index
is an int
but the action method it's being used as expects an object (id
) there, not an int
. The signature of an action method is:
- (void)methodName:(id)sender;
Or, when used with Interface Builder:
- (IBAction)methodName:(id)sender;
(IBAction
is an alias of void
. The two are semantically different but functionally identical.)
Where sender
is the object that sent the action message--in this case, the object you created and assigned to the slot
variable.
You don't include any argument names in the selector:
@selector(moveChosen:)
Selectors don't allow for binding parameters.
Georg is partially correct. For your example, it would be:
@selector(moveChosen:)
But note: if you have more than one parameter, you do include the formal parameter names to get the selector. If your function signature were:
- (void)moveChosen:(int)index withThing:(Thing*)thing
then the selector would be:
@selector(moveChosen:withThing:)
The selector is just the name of the message that you want to send. The arguments will be provided when it is called — which means CCMenuItemImage will decide what argument is passed. If CCMenuItemImage does not support providing an integer parameter, you can't make it do that.
精彩评论