相信接触过ios开发的人来说对NSNotificationCenter都不陌生。而在cocos2d-x中也参照这个类,提供了CCNotificationCenter这个类,用作通知中心。
那么NotificationCenter的介绍请看这篇文章:点击打开链接
而我主要是使用NotificationCenter 进行不同类之间的参数传递。(譬如说在两个layer之间进行参数的传递)
下面对这个CCNotificationCenter类如何使用进行简单的介绍。
1、首先这个类的位置:cocos2dx/support
2、
注意这是一个单例类
使用时要获取到单例对象:
/** Gets the single instance of CCNotificationCenter. */
static CCNotificationCenter *sharedNotificationCenter(void);
发送通知:
主要用到的两个方法:
void postNotification(const char *name);
void postNotification(const char *name, CCObject *object);
例子:
// Define this at the header
#define MY_NOTIFICATION "MY_NOTIFICATION"
CCNotificationCenter::sharedNotificationCenter()->postNotification(MY_NOTIFICATION, (CCObject*)1);
接收通知(添加监听):
方法:
void addObserver(CCObject *target,
SEL_CallFuncO selector,
const char *name,
CCObject *obj);
例子:
CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(HelloWorld::myNotification), MY_NOTIFICATION, NULL);
// Handle the notification
void HelloWorld::myNotification(CCObject* obj)
{
CCLOG("Notification achieved. ID: %i", (int)obj);
}
注意:一般的在接受通知的一方在接受完通知后需要remove监听。
方法:
void removeObserver(CCObject *target,const char *name);
int removeAllObservers(CCObject *target);
(注意第二个方法: returns the number of observers removed)
例子:
HelloWorld::~HelloWorld()
{
CCNotificationCenter::sharedNotificationCenter()->removeObserver(this, MY_NOTIFICATION);
// CCNotificationCenter::sharedNotificationCenter()->removeAllObservers(this);
}
很简单吧!
参考文章: http://www.plungeinteractive.com/blog/2012/09/20/notification-center-extension-for-cocos2d-x/
补充 :
最近在使用CCNotificationCenter 在两个 scene 之间传递参数的过程中遇到一个很容易出错的细节,下面简单记录一下。
我们知道,使用 CCNotificationCenter 在两个 scene 之间传递参数,接受方scene 要添加监听,也就是 addObserver ;而发送方scene是要发送消息,也就是 postNotification。
那么二者有先后的顺序吗?
注意:一定要先注册监听,然后发送消息,这样才可以实现数据的传递。--- 当然,这个也是很容易理解的吧。
而我就恰恰没有注意到这个问题,所以导致无法传递数据。
void HelloWorld::displayCallBack(cocos2d::CCNode *pNode)
{
//发送消息
CCNotificationCenter::sharedNotificationCenter()->postNotification(MNOTIFICATION, (CCObject*)1);
CCScene* scene = TargetRunScene::scene();
CCDirector::sharedDirector()->pushScene(CCTransitionSlideInL::create(0.8f, scene));
}
注意到:消息的接受方是 TargetRunScene ,那么我现实发送了消息,然后才初始化接受方的 scene,那么显然接收方的添加监听是在发送了消息后的,所以这样的话,是无法传递参数的。
那么,如何解决呢?
简单啦,就是讲发送消息的放在TargetRunScene 初始化之后就可以了。
void HelloWorld::displayCallBack(cocos2d::CCNode *pNode)
{
CCScene* scene = TargetRunScene::scene();
CCDirector::sharedDirector()->pushScene(CCTransitionSlideInL::create(0.8f, scene));
//发送消息
CCNotificationCenter::sharedNotificationCenter()->postNotification(MNOTIFICATION, (CCObject*)1);
}