Cocos2d-x CCNotificationCenter 通知中心

  相信接触过ios开发的人来说对NSNotificationCenter都不陌生。而在cocos2d-x中也参照这个类,提供了CCNotificationCenter这个类,用作通知中心。而我主要是使用NotificationCenter 进行不同类之间的参数传递。(譬如说在两个layer之间进行参数的传递)

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

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

2、注意这是一个单例类使用时要获取到单例对象

常用方法:

NotificationCenter::getInstance();  //获取实例

void addObserver(CCObject *target, SEL_CallFuncO selector, const char *name, CCObject *obj);   //添加监听
void removeObserver(CCObject *target,const char *name);  //删除监听
int removeAllObservers(CCObject *target);  

发送通知:

主要用到的两个方法:

void postNotification(const char *name);  
void postNotification(const char *name, CCObject *object); 

例子:

#define MY_NOTIFICATION "MY_NOTIFICATION"    //定义消息

CCNotificationCenter::sharedNotificationCenter()->postNotification(MY_NOTIFICATION, (CCObject*)1);    //Post 消息

CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(HelloWorld::myNotification), MY_NOTIFICATION, NULL);   //注册监听

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

  注:使用 CCNotificationCenter 在两个 scene 之间传递参数,接受方scene 要添加监听,也就是 addObserver ;而发送方scene是要发送消息,也就是 postNotification。一定要先注册监听,然后发送消息,这样才可以实现数据的传递。

 

原文地址:https://www.cnblogs.com/DswCnblog/p/3664646.html