使用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);
- }