Call a static method and use parameters in a menu_selector

Call a static method and use parameters in a menu_selector
0.0 0


I have the following code:

CCLabelBMFont label = CCLabelBMFont::labelWithString;
back = CCMenuItemLabel::itemWithLabel(label, this, menu_selector(OptionsScene::backCallback) );

void OptionsScene::backCallback(CCObject* sender)
CCLog(“do nothing”);

It works ok, because I call ‘OptionsScene::backCallback’, and this method is inside that class, but I want to call a static method from another class, for example, this following code:

void HelloWorld::show()
CCLog(“i’m STATIC”);

is inside HelloWorld class,

I’am new to c++, I sucessfully call the static method from another class, but I can’t call it using the ‘menu_selector’ option from a CCMenuItemLabel


You can’t pass static method to CCMenuItemLabel because it expects nonstatic method (in C++ all nonstatic methods get hidden first argument which is used as “this” pointer - analogue to “self”). So you need to make the method you pass nonstatic or write a nonstatic wrapper for it.


I understand, thanks for the explanation.
One more thing, it’s possible to pass parameters using nonstatic methods in menu_selector, for example

void OptionsScene::randomValueBetween( float low , float high ) {}

CCMenuItemLabel back = CCMenuItemLabel::itemWithLabel(label, this, menu_selector(OptionsScene::randomValueBetween(1,2)) );

I try this code and not work for me.


This isn’t possible. The method type for callback is defined in CCObject.h as follows:

typedef void (CCObject::*SEL_MenuHandler)(CCObject*);

This means your method must have the following signature:

void YourClass::yourMethodName(CCObject* pSender);

The only parameter is the pointer to calling object (it is the menu item itself). You can use pSender pointer to obtain the data you need or get it from another source.


How I can get the data from pSender?

Using the following code:

CCMenuItemToggle* item1 = CCMenuItemToggle::itemWithTarget( this, menu_selector(OptionsScene::menuCallback), CCMenuItemFont::itemFromString( “On” ), CCMenuItemFont::itemFromString( “Off”), CCMenuItemFont::itemFromString( “Rock1”), NULL );

void OptionsScene::menuCallback(CCObject* sender)
CCLog(“selected item: %@”, (sender)->getStringFromSelectedIndex );

It’s possible to get the String from the selected index object from CCMenuItemToogle.

I accept any suggest because it’s hard for me to maintain the code the way that I know.


Your sender will be CCMenuItemToggle. You need to invoke sender->selectedItem() to get the CCMenuItemFont item. I see no way to get the string back from CCMenuItemFont.


It’s not possible to get the selectedIndex from CCMenuItemToggle?


Yes, getSelectedIndex().


It works,
I use the code based in the test folder of cocos2d-x

void OptionsScene::menuCallback(CCObject* sender)
CCLog(“selected item: %x”, dynamic_cast<CCMenuItemToggle*>(sender)->getSelectedIndex() );

thank you, you helped me a lot