转自 点击打开链接
CCNotificationCenter事件监听器也好,观察者模式也罢,这个东西的用处就是用在俩个类通信的时候,一个类用来发送消息,一个类用来接收消息。其实这个东西的用处是非常大的,举个例子吧。比如一片草地,会在不同的季节反应出不同的状态,春天的时候草长了出来,都是绿的,夏天的时候草长的更高了,秋天的时候又会变颜色,在四季更换的不同状态下,草的颜色也会跟着发生改变,也就是会对应不同的状态,这个天气信息就可以看成发送过来的消息,而对这些消息的处理就是状态之间的相互切换。我也不知道说的正确不正确,但是推荐给大家一篇博客,不理解的可以看看。事件驱动,你想象不到的强大。下面我来说说怎么用这个东西,以及用的时候要注意的一些问题。
2 | #ifndef _NOTIFICATION_H_ |
3 | #define _NOTIFICATION_H_ |
5 | #define MY_NOTIFICATION "Hello" |
CCNotification采用了单例的
设计模式
,使用函数addObserver来监听消息。这段代码我写在了init中。
3 | CCNotificationCenter::sharedNotificationCenter()->addObserver( this , |
4 | callfuncO_selector(TestScene::getNotification),MY_NOTIFICATION,NULL); |
3 | CCNotificationCenter::sharedNotificationCenter()->addObserver( this , |
4 | callfuncO_selector(TestScene::getNotification),MY_NOTIFICATION,NULL); |
2 | void TestScene::getNotification(CCObject * object) |
4 | int * i = ( int *)object; |
5 | CCLog( "HelloWorld i = %d" ,i); |
接下来就是使用post来发送消息了。
1 | void HelloWorld::menuCloseCallback(CCObject* pSender) |
5 | CCDirector::sharedDirector()->replaceScene(TestScene::scene()); |
8 | CCNotificationCenter::sharedNotificationCenter()->postNotification(MY_NOTIFICATION,(CCObject *)1); |
释放消息一般写在onExit()函数中,就是谁监听消息,谁释放消息。
1 | void TestScene::onExit() |
4 | CCNotificationCenter::sharedNotificationCenter()->removeObserver( this ,MY_NOTIFICATION); |
3 | CCNotificationCenter::sharedNotificationCenter()->addObserver( this , |
4 | callfuncO_selector(TestScene::getNotification),MY_NOTIFICATION,NULL); |