相信接触过ios开发的人来说对NSNotificationCenter都不陌生。而在cocos2d-x中也参照这个类,提供了CCNotificationCenter这个类,用作通知中心。
而我主要是使用 NotificationCenter 进行不同类之间的参数传递。(譬如说在两个layer之间进行参数的传递)
下面对这个 CCNotificationCenter类如何使用进行简单的介绍。
1、首先这个类的位置:cocos2dx/support
发送通知:
CCNotificationCenter::sharedNotificationCenter()->postNotification(MY_NOTIFICATION, (CCObject*)1);
先添加观察者,然后再发送通知
接收通知(添加监听)
CCNotificationCenter::sharedNotificationCenter()-]]>addObserver(this, callfuncO_selector(HelloWorld::myNotification), MY_NOTIFICATION, NULL);
看一下定义
@param target The target which wants to observe notification events.
@param selector The callback function which will be invoked when the specified notification event was posted.
@param name The name of this notification.
@param obj The extra parameter which will be passed to the callback function.
void addObserver(CCObject *target,
SEL_CallFuncO selector,
const char *name,
CCObject *obj);
// Handle the notification void HelloWorld::myNotification(CCObject* obj) { CCLOG("Notification achieved. ID: %i", (int)obj); }
注意:一般的在接受通知的一方在接受完通知后需要remove监听。
HelloWorld::~HelloWorld() { CCNotificationCenter::sharedNotificationCenter()->removeObserver(this, MY_NOTIFICATION); // CCNotificationCenter::sharedNotificationCenter()->removeAllObservers(this);}