NotificationCenterを使う

今まであまり気にしていなかったのですが、NotificationCenterの仕組みが便利であることがわかったので、
その使い方をメモ。

今回使用したバージョン

  • Cocos2d-x 3.1

呼び出される側の実装

     // コンストラクタ
     HelloWorld::HelloWorld()
     {
          NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(HelloWorld::method1), "キー名", NULL);
     }
     // デストラクタ
     HelloWorld::~HelloWorld()
     {
          NotificationCenter::getInstance()->removeAllObservers(this);
     }
     
     // 実行されるメソッド
     void HelloWorld::method1(cocos2d::Ref* sender)
     {
          
     }

呼び出す側の実装

     NotificationCenter::getInstance()->postNotification("キー名");

SpriteクラスからLayerクラスのメソッドを呼び出したり、Layerクラスから全てのSpriteクラスに命令したりと、
便利に使うことができます。