cocos2dx3.3 CCNotificationCenter观察者模式

来源:互联网 发布:听歌不要钱的软件 编辑:程序博客网 时间:2024/06/05 18:11

     在游戏中经常用会遇到两个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
原创粉丝点击