CCNotificationCenter实现类之间的数据通信
画图分析
CCNotificationCenter是什么?
CCNotificationCenter是集消息管理和管理观察者与被观察者之间关系功能的单例类。
通过sharedNotificationCenter()方法获取CCNotificationCenter的实例;
通过addObserver方法建立观察者与被观察者之间的关系,通过一个字符串key与一个Observer指针列表建立关系;
通过postNotification方法发送通知;
通过removeObserver方法移除观察者;
示例
说明:在A类(NotifyTest)中定义通知回调方法、注册和移除观察者,在B类中发送通知。
1.定义通知回调函数
void notifyTest(CCObject* pSender);
2.添加观察者
//定义一个字符串key #define CLOSE_NOTIFY "CLOSE"
CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(NotifyTest::notifyTest), CLOSE_NOTIFY, NULL);
3.发送通知
//第一个参数是key,第二个参数是通知回调方法的参数 CCNotificationCenter::sharedNotificationCenter()->postNotification(CLOSE_NOTIFY,CCInteger::create(100));
4.移除观察者
//在通知回调方法里打印参数,并移除观察者
void NotifyTest::notifyTest(CCObject* pSender){
int value = ((CCInteger*)pSender)->getValue();
CCLOG("call notifyTest pSender=%d",value);
//3.移除观察者
CCNotificationCenter::sharedNotificationCenter()->removeObserver(this,CLOSE_NOTIFY);
}运行效果:
posted on 2014-07-22 00:20 linchaolong 阅读(216) 评论(0) 收藏 举报
浙公网安备 33010602011771号