cocos2d-x中CCNotificationCenter(消息中心)的应用

参考博文: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());

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值