游戏中经常遇到几个层之间互相通信的问题。比如,在游戏界面时,可以打开音乐设置界面,弹出音乐设置界面需要暂停游戏,当设置好音乐时回到游戏界面时,游戏要启动继续游戏,如果添加头文件或者不能互相添加头文件时,可以用此方法很实用的。
1. 在需要发送消息的地方(比如点击下一关按钮的回调函数),post消息即可,post有两种类型,带数据和不带数据:
void postNotification(const char *name);
void postNotification(const char *name, CCObject *object);
name:消息的名称,可以当成是消息的唯一标识,一般这样定义name:
const char * const myName = "myname";
例如:CCNotificationCenter::sharedNotificationCenter()->postNotification(myName, (CCObject*)1);
2. 在任何地方,只要你对某个消息感兴趣,你就可以在那里监听该消息。假如你对HelloWorld类,myName消息感兴趣。
例如:CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(HelloWorld::myFunction), myName, NULL);
void HelloWorld::myFunction(CCObject* obj)
{
//这里写接收消息后需要处理的事情
}
3. 注意:一般的在接受通知的一方在接受完通知后需要remove监听。
例如:
HelloWorld::~HelloWorld()
{
CCNotificationCenter::sharedNotificationCenter()->removeObserver(this, myName);
}
4. 需要注意的一点是,必须要先注册监听,再调用发送,要不然就会监听不到消息。