ioscocos2d-iphoneselectorccmenuitem

Cocos2d: call selector in selected method of CCMenuItem


I would like to call the target selector (see below: buttonPressedWithId:) when the "selected" method of a CCMenuItemSprite is called.

 CCMenuItemSprite *buttonB = [CCMenuItemSprite itemWithNormalSprite:[CCSprite spriteWithSpriteFrameName:@"emptyCircle.png"] selectedSprite:[CCSprite spriteWithSpriteFrameName:@"greenCircle.png"] target:self  selector:@selector(buttonPressedWithId:)];

I looked into the implementation of CCMenuItemSprite and found this:

-(void) selected
{
    [super selected];
    //HERE IS WHERE I WANT TO CALL buttonPressedWithId: 
    if( selectedImage_ ) {
        [normalImage_ setVisible:NO];
        [selectedImage_ setVisible:YES];
        [disabledImage_ setVisible:NO];

    } else { // there is not selected image

        [normalImage_ setVisible:YES];
        [selectedImage_ setVisible:NO];
        [disabledImage_ setVisible:NO];
    }
}

The goal would be to call the targeted selector in the selected method. So I looked into the initWithNormalSprite method and found:

-(id) initWithNormalSprite:(CCNode<CCRGBAProtocol>*)normalSprite selectedSprite:(CCNode<CCRGBAProtocol>*)selectedSprite disabledSprite:(CCNode<CCRGBAProtocol>*)disabledSprite target:(id)target selector:(SEL)selector
{
    // avoid retain cycle
    __block id t = target;

    return [self initWithNormalSprite:normalSprite selectedSprite:selectedSprite disabledSprite:disabledSprite block:^(id sender) {
        [t performSelector:selector withObject:sender];
    } ];
}

I guess I have somehow to call the _block function but I don't see a good example to understand how. I also have not much idea of what *_block* is :(.

Now, should I sublcass CCMenuItemSprite and change this beheaviour? And if so, how can I call the targeted selector?

Thanks in advance :)


Solution

  • there is -activate method in superclass of CCMenuItemSprite - CCMenuItem. So if you want, you could subclass CCMenuItemSprite and make its -selected method looks like this:

    -(void) selected
    {
        [super selected];
        [self activate];
    }
    

    also you could see into the code of -activate, it is very simple :)