开发时,在层或者场景之间进行数据的消息的传递是时常需要的。
cocos2d-x框架中内置的观察者模式封装了一个CCNotificationCenter单例类,也被称为消息通知中心。
CCNotificationCente主要API(CCNotificationCente官方文档连接)
CCNotificationCenter ()
~CCNotificationCenter ()
void addObserver (CCObject *target, SEL_CallFuncO selector, const char *name, CCObject *obj)
void removeObserver (CCObject *target, const char *name)
int removeAllObservers (CCObject *target)
void postNotification (const char *name)
void postNotification (const char *name, CCObject *object)
CCNotificationCente的实现机制是 一个对象通过addObserver注册观察者,并通过消息名称(const char *name)对目标进行监测,当目标对象状态发生变化时,即目标对象通过postNotification发送消息,该对象便做出相应反应。
而目标对象可以通过postNotification发送带数据的消息和不带数据的消息。层或者场景之间便可通过postNotification发送带数据的消息进行传递消息和数据。
下面举个列子(代码不完整)
// A layer
bool A::init(){
if (!Layer::init()) {
return false;
}
CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(A::getMessage), "sendmessage", NULL);
return true;
}
void A::getMessage(CCObject* obj){
int getNumber = (int)obj;
}
// B Layer
bool B::init(){
if (!Layer::init()) {
return false;
}
int sendNumber = 1;
CCNotificationCenter::sharedNotificationCenter()->postNotification("sendmessage",(CCObject*)sendNumber);
return true;
}
层或者场景之间便可通过CCNotificationCenter的postNotification发送带数据的消息进行传递基本类型的消息和数据,但是若是传输vector之类的容器里的数据,则是行不通的,因为参数并不匹配。
那么可以通过观察者获取postNotification发送不带数据的消息,进行主动获取目标对象的相应的信息。
//(代码不完整)
// A Layer
class A:public cocos2d::Layer{
private:
B* b;
}
bool A::init(){
if (!Layer::init()) {
return false;
}
CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(A::getMessage), "sendmessage", NULL);
return true;
}
void A::getMessage(CCObject* obj){
vector<int> IntVector=b->getVectorMessage();
}
// B Layer
class B:public cocos2d::Layer{
public:
void getVectorMessage();
private:
vector<int> IntVector;
}
B::init(){
if (!Layer::init()) {
return false;
}
CCNotificationCenter::sharedNotificationCenter()->postNotification("sendmessage");
return true;
}
这个方法可以在B层有操作的情况,通过观察者模式,向A层发送消息,让A层主动调取B层中操作完的vector等容器的消息和数据。