在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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。