0

My CCMenuItem has two methods in selector

        menuItem = [[CCMenuItemSprite
                         itemFromNormalSprite:[CCSprite spriteWithSpriteFrameName:@"menuItem.png"]
                         selectedSprite:[CCSprite spriteWithSpriteFrameName:@"menuItem.png"]
                         target:self
                         selector:@selector(methodName:anotherParam:)] retain];

I'd like to send the an int from CCMenuItem so that I'd could switch the cases based on the int of the CCMenuItem

something like this:

- (void)methodName:(id *)sender anotherParam:(int *)intNumber {
    CCMenuItemSprite *menuItem = (CCMenuItemSprite *)sender;

    switch (anotherParam) {
        case 1:
        //My case
        break;
}

How can I send an int from CCMenuItem in order to switch my cases?

2 Answers 2

3

You can use the userData property of a CCNode for this, or you could set an associated object.

Eample:

CCNode *myNode = [CCNode node];
myNode.userData = (void *) intVal;

// in callback
CCNode *myNode = (CCNode *) sender;
int anotherParam = (int) myNode.userData; 

To set an associated object, you would do something like this:

objc_setAssociatedObject(myObject, "anotherParam", (id) myInt, OBJC_ASSOCIATION_ASSIGN);

// in callback
int anotherParam = (int) objc_getAssociatedObject(myObject, "anotherParam");

Note that key is of type void * so you could put any value there (NSObject, NSString, C-string, int value, etc.)

5
  • Where I should place objc_setAssociatedObject ?
    – el.severo
    Feb 6, 2012 at 14:17
  • @el.severo when you initialize the object. Feb 6, 2012 at 14:21
  • Complier complains with the following errors: Implicit declaration of function 'obj_setAssociatedObject' is invalid in C99 & Use of undeclared identifier 'OBJC_ASSOCIATION_ASSIGN'
    – el.severo
    Feb 6, 2012 at 14:44
  • Did you import <objc/runtime.h>? And the function is objc_setAssociatedObject, not obj_setAssociatedObject. Feb 6, 2012 at 14:46
  • let us continue this discussion in chat
    – el.severo
    Feb 6, 2012 at 14:51
2

Just tag the CCMenuItem:

menuItem.tag = 1;

Then get it from the sender parameter:

- (void)methodName:(id *)sender { 

    switch ([sender tag]) {
       //cases depending on tag
    }
}
3
  • I don't want that much cases... only few of them
    – el.severo
    Feb 6, 2012 at 14:20
  • I've grouped my CCMenuitems into cases and want to remove in a certain order; disabled all except frist case and I'm getting them by tag to enable it
    – el.severo
    Feb 6, 2012 at 14:25
  • 1
    I'm afraid I don't really understand what you mean sorry. If you have given them all a tag, I don't see what the issue is.
    – FBryant87
    Feb 6, 2012 at 14:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.