Cocos2d-x CCNotificationCenter

来源:互联网 发布:淘宝退换货规则 编辑:程序博客网 时间:2024/06/04 18:17

使用NotificationCenter 进行不同类之间的参数传递。(譬如说在两个layer之间进行参数的传递)

下面对这个CCNotificationCenter类如何使用进行简单的介绍。

1、首先这个类的位置:cocos2dx/support

2、

注意这是一个单例类

使用时要获取到单例对象:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** Gets the single instance of CCNotificationCenter. */  
  2.     static CCNotificationCenter *sharedNotificationCenter(void);  

发送通知:

主要用到的两个方法:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. void postNotification(const char *name);  
  2.   
  3. void postNotification(const char *name, CCObject *object);  

例子:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. // Define this at the header  
  2. #define MY_NOTIFICATION "MY_NOTIFICATION"  

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. CCNotificationCenter::sharedNotificationCenter()->postNotification(MY_NOTIFICATION, (CCObject*)1);  

接收通知(添加监听):

方法:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. void addObserver(CCObject *target,   
  2.                      SEL_CallFuncO selector,  
  3.                      const char *name,  
  4.                      CCObject *obj);  

例子:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(HelloWorld::myNotification), MY_NOTIFICATION, NULL);  

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. // Handle the notification  
  2. void HelloWorld::myNotification(CCObject* obj)  
  3. {  
  4.     CCLOG("Notification achieved. ID: %i", (int)obj);  
  5. }  

注意:一般的在接受通知的一方在接受完通知后需要remove监听。

方法:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. void removeObserver(CCObject *target,const char *name);  
  2.   
  3. int removeAllObservers(CCObject *target);  

(注意第二个方法: returns the number of observers removed)

例子:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. HelloWorld::~HelloWorld()  
  2. {  
  3.     CCNotificationCenter::sharedNotificationCenter()->removeObserver(this, MY_NOTIFICATION);  
  4.       
  5. //    CCNotificationCenter::sharedNotificationCenter()->removeAllObservers(this);  
  6. }  

0 0