Cocos2dx 學習筆記26 CCNotificationCenter的使用

在ios開發中,經常會使用到通知這種模式,在coscos2dx中也移植了這種模式,CCNotificationCenter

CCNotificationCenter被設計成了一個單例模式。其使用方法和OC中差不多,在ios開發中經常是再一個界面出現或初始化的時候,註冊消息通知,在界面消失時取消通知。CCNotificationCenter的用法如下:

先來看下cocos2dx中註冊通知的函數:

/** @brief Adds an observer for the specified target.
     *  @param target The target which wants to observe notification events.
     *  @param selector The callback function which will be invoked when the specified notification event was posted.
     *  @param name The name of this notification.
     *  @param obj The extra parameter which will be passed to the callback function.
     */
    void addObserver(CCObject *target, 
                     SEL_CallFuncO selector,
                     const char *name,
                     CCObject *obj);


由此可見我們該這樣來添加一個觀察者: 

CCNotificationCenter::sharedNotifCenter()->addObserver(this,callfuncO_selector(HelloWorld::menuCloseCallback), TONGZHI, NULL);  //註冊消息


void HelloWorld::menuCloseCallback(CCObject* pSender)
{
    //移除監聽事件
    CCLog("收到監聽 並且移除!");
    CCNotificationCenter::sharedNotifCenter()->removeObserver(this, TONGZHI);
}




寫好以後 只要在需要的地方拋出通知 即可


 
 CCNotificationCenter::sharedNotifCenter()->postNotification(TONGZHI,NULL);



發佈了23 篇原創文章 · 獲贊 1 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章