addObserver这个函数一般是用来接收消息的,但是这个函数的定义如下:
void __NotificationCenter::addObserver(Ref *target,
SEL_CallFuncO selector,
const std::string& name,
Ref *sender)其最后一个参数也可以传递一个数据,这个数据可以被自己接收到。
下面是一个简单的例子:
第一个层中的定义:
bool HelloWorld::init()
{
scheduleOnce(schedule_selector(HelloWorld::sendMsg), 3.0f);
//在3秒后调用sendMsg函数
return true;
}
void HelloWorld::sendMsg(float dt){
NotificationCenter::getInstance()->postNotification("Hello", NULL);
//发送消息,消息名称为"Hello"
}第二个层中的定义:
bool GameScene::init(){
NotificationCenter::getInstance()->
addObserver(this, callfuncO_selector(GameScene::Hello), "Hello", (Ref*)"World");
//检测名为"Hello"的消息,如果接收到,则调用函数Hello
return true;
}
void GameScene::Hello(Ref* pData){
log("Hello %s",pData);
}可见发送的时候并没有发送在postNotification中发送消息的内容,但是将addObserver中最后一个参数设置为(Ref*)"World".
调试该程序,可以发现程序的输出为:
Hello World
这说明GameScene::Hello这个函数获取到了addObserver传出去的参数。
有些书上说addObserver的最后一个参数是起到一个过滤作用。
我自己的结论是,当postNotification不传输内容时,addObserver的最后一个参数会作为数据传递给调用的函数。当postNotification有传输内容时,addObserver的最后一个参数起过滤作用,也就是说如果两个函数传输的内容不同时,无法接收数据。
在上面的例子上做一点修改:
void HelloWorld::sendMsg(float dt){
NotificationCenter::getInstance()->postNotification("Hello", (Ref*)"233");
//发送消息,消息名称为"Hello"
}此时,调试程序可以发现没有任何输出,可见获取端没有接收到数据。
如果postNotification传输的内容和addObserver的内容一致时,是可以接收到数据的,如下:
void HelloWorld::sendMsg(float dt){
NotificationCenter::getInstance()->postNotification("Hello", (Ref*)"World");
//发送消息,消息名称为"Hello"
}此时,调试程序,输出如下:
Hello World
可见此时是可以正常接收数据的。这种情况下,addObserver的最后一个参数就起到了对接收的消息的过滤作用。
本文探讨了Cocos2d-x的addObserver函数如何传递消息。通过示例,解释了当postNotification无内容时,addObserver的最后一个参数作为数据传递,而当有内容时,该参数用于过滤不同消息。只有当postNotification传输的内容与addObserver匹配时,才能成功接收数据。
183

被折叠的 条评论
为什么被折叠?



