参考博文:http://blog.csdn.net/jackystudio/article/details/17088979
主要描述CCNotificationCenter在层与层或层与场景、场景与场景之间的消息传递。
(1)ALayer.h
#pragma once
#include "cocos2d.h"
USING_NS_CC;
class ALayer : public CCLayer{
public:
ALayer(void);
~ALayer(void);
CREATE_FUNC(ALayer);
virtual bool init();
void postMsg(CCObject* pSender);
};
(2)ALayer.cpp
#include "ALayer.h"
ALayer::ALayer(void){
}
ALayer::~ALayer(void){
}
bool ALayer::init(){
bool bRet = false;
do
{
CC_BREAK_IF(!CCLayer::init());
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCMenuItemImage* m_closeItem = CCMenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
this,
menu_selector(ALayer::postMsg)
);
m_closeItem->setAnchorPoint(ccp(0.5,0.5));
m_closeItem->setPosition(ccp(visibleSize.width/2, visibleSize.height/2));
CCMenu* m_menu = CCMenu::create(m_closeItem,NULL);
m_menu->setPosition(CCPointZero);
this->addChild(m_menu,1);
bRet = true;
} while (0);
return bRet;
}
void ALayer::postMsg(CCObject* pSender){
CCString* str = CCString::create("Hello BLayer");
//往notificationCenter发送消息.参数1为消息的名称,参数2为消息内容
CCNotificationCenter::sharedNotificationCenter()->postNotification("BMsg",str);
}
(3)BLayer.h
#pragma once
#include "cocos2d.h"
USING_NS_CC;
class BLayer : public CCLayer{
public:
BLayer(void);
~BLayer(void);
CREATE_FUNC(BLayer);
virtual bool init();
void getMsg(CCObject* pSender);
};
(4)BLayer.cpp
#include "BLayer.h"
BLayer::BLayer(void){
}
BLayer::~BLayer(void){
//释放通知中心单例对象
CCNotificationCenter::sharedNotificationCenter()->purgeNotificationCenter();
}
bool BLayer::init(){
bool bRet = false;
do
{
CC_BREAK_IF(!CCLayer::init());
//添加观察者
CCNotificationCenter::sharedNotificationCenter()->addObserver(this,callfuncO_selector(BLayer::getMsg),"BMsg",NULL);
bRet = true;
} while (0);
return bRet;
}
void BLayer::getMsg(CCObject* obj){
CCString* str = (CCString*)obj;
CCLOG(str->getCString());
}