首先需要说明在
CCNotificationCenter::sharedNotificationCenter()->addObserver(cocos2d::CCObject *target, SEL_CallFuncO selector, const char *name, cocos2d::CCObject *obj)
和
CCNotificationCenter::sharedNotificationCenter()->postNotification(const char *name, cocos2d::CCObject *object)
这两个函数中,最后的那个obj参数都是传的消息内容,但是这两个函数里面只能有一个函数里面有,或者有一个为空,如果两者都不一样并且都不为空,那么消息是发不出来的,这个可以看内部代码.
Demo示例
这个demo在Helloword里面发送一个消息,标识是"test",会同时响应helloword类和secondScene的消息
HelloWorldScene.h文件
#ifndef __HELLOWORLD_SCENE_H__define __HELLOWORLD_SCENE_H__
include "cocos2d.h"
class HelloWorld : public cocos2d::CCLayer
{
public:
virtual bool init();
static cocos2d::CCScene* scene();
CREATE_FUNC(HelloWorld);
void sendMeg();
void getMeg(void *mes);
};endif // __HELLOWORLD_SCENE_H__
HelloWorldScene.m文件
#include "HelloWorldScene.h"include "SecondScene.h"
USING_NS_CC;
CCScene* HelloWorld::scene()
{
CCScene *scene = CCScene::create();
HelloWorld *layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}bool HelloWorld::init()
{
if ( !CCLayer::init() )
{
return false;
}
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
CCMenuItemImage *item=CCMenuItemImage::create("Icon-57.png", "Icon-57.png",this,menu_selector(HelloWorld::sendMeg));
CCMenu *menu=CCMenu::createWithItem(item);
menu->setPosition((origin.x+visibleSize.width)/2, (origin.y+visibleSize.height)/2);
addChild(menu);
//注册helloworld
CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(HelloWorld::getMeg), "test",NULL);
//注册second
SecondScene *scend=new SecondScene();
scend->addobj();
return true;
}
void HelloWorld::sendMeg()
{
CCNotificationCenter::sharedNotificationCenter()->postNotification("test",(CCObject*)"helloworldtest");
}
void HelloWorld::getMeg(void *mes)
{
CCLOG("helloworld:%s",mes);
}
SecondScene.h文件
#ifndef __NoticeDemo__SecondScene__define __NoticeDemo__SecondScene__
include <stdio.h>
include "cocos2d.h"
USING_NS_CC;
class SecondScene:public CCObject
{
public:
SecondScene();
~SecondScene();
void addobj();
void getMeg(void* meg);
};endif / defined(__NoticeDemo__SecondScene__) /
SecondScene.m文件
#include "SecondScene.h"SecondScene::SecondScene()
{
}
void SecondScene::addobj()
{
CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(SecondScene::getMeg), "test", NULL);
}
SecondScene::~SecondScene()
{
}
void SecondScene::getMeg(void* meg)
{
CCLOG("secondscene:%s",meg);
}
当点击按钮的时候,会同时打印两行输出,输出内容就是传递的参数<br/>
版权属于:胡东东博客
本文链接:https://blog.hudongdong.com/cocos2d/70.html
自2017年12月26日起,『转载以及大段采集进行后续编辑』须注明本文标题和链接!否则禁止所有转载和采集行为!
☟☟如文章有用,可点击一次下方广告支持一下☟☟