cocos2dx3.3 CCNotificationCenter观察者模式

     在游戏中经常用会遇到两个layer之间通信或者一对多的关系时(比如一个精灵的状态改变会相应触发一些动作效果和数据的改变)这时候应该使用观察者模式,cocos2d中使用CCNotificationCenter来实现观察者模式。

     即消息的注册和消息的触发 

     注册消息

     addObserver(Ref *target, SEL_CallFuncO selector,const std::string& name,Ref *sender); 

     第一个参数target主体对象一般为this,第二个参数为当消息触发时要调用的函数,第三个参数为该消息的标识符,第四个参数为要传递的数据。CCNotificationCenter本身也是单利模式,所以此函数的用法为

CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(ChinesePath::hhh),"hello",NULL);
     触发消息

     void postNotification(const std::string& name, Ref *sender);

     一个参数为要触发的消息标识符,第二个参数为要传递的数据。用法为

<span style="font-family:SimHei;"> CCNotificationCenter::sharedNotificationCenter()->postNotification("hello",(CCObject *)1);</span>
<span style="font-family:SimHei;">    如果只注册消息而不回收消息则会到底内存泄漏</span><pre name="code" class="html">    void removeObserver(Ref *target,const std::string& name);
    根据消息标识符回收
    int removeAllObservers(Ref *target);
    回收所有的消息,返回回收的消息数目

 




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值