Cocos2d-x层/场景之间的vector数据的传递

9 篇文章 0 订阅

开发时,在层或者场景之间进行数据的消息的传递是时常需要的。

cocos2d-x框架中内置的观察者模式封装了一个CCNotificationCenter单例类,也被称为消息通知中心。

CCNotificationCente主要API(CCNotificationCente官方文档连接

 CCNotificationCenter ()
 ~CCNotificationCenter ()

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)

CCNotificationCente的实现机制是 一个对象通过addObserver注册观察者,并通过消息名称(const char *name)对目标进行监测,当目标对象状态发生变化时,即目标对象通过postNotification发送消息,该对象便做出相应反应。

而目标对象可以通过postNotification发送带数据的消息和不带数据的消息。层或者场景之间便可通过postNotification发送带数据的消息进行传递消息和数据。

下面举个列子(代码不完整)

// A layer
bool A::init(){
  if (!Layer::init()) {
        return false;
  }
  CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(A::getMessage), "sendmessage", NULL);
  return true;
}
void A::getMessage(CCObject* obj){
  int getNumber = (int)obj;
}

// B Layer
bool B::init(){
  if (!Layer::init()) {
        return false;
  }
 int sendNumber = 1;
  CCNotificationCenter::sharedNotificationCenter()->postNotification("sendmessage",(CCObject*)sendNumber);
  return true;
}

层或者场景之间便可通过CCNotificationCenter的postNotification发送带数据的消息进行传递基本类型的消息和数据,但是若是传输vector之类的容器里的数据,则是行不通的,因为参数并不匹配。

那么可以通过观察者获取postNotification发送不带数据的消息,进行主动获取目标对象的相应的信息。

//(代码不完整)
// A Layer
class A:public cocos2d::Layer{
private:
  B* b;
}

bool A::init(){
  if (!Layer::init()) {
        return false;
  }
  CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(A::getMessage), "sendmessage", NULL);
  return true;
}
void A::getMessage(CCObject* obj){
  vector<int> IntVector=b->getVectorMessage();
}

// B Layer
class B:public cocos2d::Layer{
public:
  void getVectorMessage();
private:
  vector<int> IntVector;
}
B::init(){
  if (!Layer::init()) {
        return false;
  }
  CCNotificationCenter::sharedNotificationCenter()->postNotification("sendmessage");
  return true;
}

这个方法可以在B层有操作的情况,通过观察者模式,向A层发送消息,让A层主动调取B层中操作完的vector等容器的消息和数据。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值