NotificationCenter的基本使用:</span>
init方法中:</span>
NotificationCenter::getInstance()->addObserver(this,callfuncO_selector(HelloWorld::call2),"abc",nullptr); //添加观察对象 auto b1 = MenuItemImage::create("CloseNormal.png","CloseNormal.png",CC_CALLBACK_0(HelloWorld::call,this)); //按钮 auto menu = Menu::create(b1,nullptr); this->addChild(menu);
对应的方法:</span>
void HelloWorld::call() { log("call()"); NotificationCenter::getInstance()->postNotification("abc",this); } void HelloWorld::call2(Ref* obj) { log("call2()"); auto s = Sprite::create("CloseNormal.png"); s->setPosition(Vec2(100,100)); this->addChild(s); }
</pre><pre name="code" class="cpp">最后:
HelloWorld::~HelloWorld() { <span style="white-space:pre"> </span>NotificationCenter::getInstance()->removeObserver(this,"abc"); //取消监听 <span style="white-space:pre"> </span>//NotificationCenter::getInstance()->removeAllObservers(this); }