Passing instance variable to selector configured in CCMenuItemImage
I need a hand passing a variable to a selector configured in a CCMenuItemImage, if that's even possible. Seems like it should be, I just can't work it out!
Here's what I'm trying to achieve:
- Crea开发者_如何学编程te menu of say 20 game levels items with for/loop. No problem.
- In the for/loop, specify incrementing variable. No problem.
- Pass incrementing variable to selector specified in CCMenuItemImage. Problem!
- Use incrementing variable to determine what game level to load when particular menu item is tapped. Problem without #3 solved!
Anyway, on with the (cut down for clarity) code:
Here's the command used within the for/loop to create the menu item
CCMenuItemImage *image = [CCMenuItemImage itemFromNormalImage:@"Normal.png" selectedImage:@"Selected.png" target:self selector:@selector(onSelect:)];
Now as you can see in the above snippet, there's no space for say 'userinfo' like the NSTimer class provides for this very purpose.
Ideally, instead of pointing each CCMenuItemImage to the same selector which I can't pass a variable to, I'd actually prefer to call a method like this one below. The int would represent the game level that should be loaded when the CCMenuItemImage is tapped:
- (void)onSelectWithStage:(int)selectedStage {
// write the selected stage to the GameData.xml
[SceneManager goLevelSelect];
}
Anyway I think that pretty much sums up the issue. Hopefully I'm missing something glaringly obvious :)
Thanks in advance for your time
Use tags!
for(int i = 0;i<MAX_LEVELS;i++)
{
CCMenuItemImage *image = [CCMenuItemImage
itemFromNormalImage:@"Normal.png"
selectedImage:@"Selected.png"
target:self
selector:@selector(onSelect:)];
image.tag = i;
}
And adjust your onSelect method accordingly.
-(void)onSelect:(CCMenuItemImage*)item{
int lvl = item.tag;
[self onSelectWithStage:lvl];
}
The approach I would take is to add the levels to an NSDictionary keyed on a CCMenuItemImage instance, so create the level, create the menu item and add the level to the dictionary keyed on its menu item.
When the selector fires, you are given a reference to the CCMenuItemImage that sent it, simply get the level from the dictionary with the key that matches the menu item.
Simples.
精彩评论