博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

NSNotificationCenter

Posted on 2011-07-12 10:07  星尘的天空  阅读(396)  评论(0编辑  收藏  举报

NSNotificationCenter的作用

NSNotificationCenter有什么作用,简单说之,就是两个不相干的对象之间可以通过他来传递消息,只要你把相关发送的消息和处理的事件在他那里注册就行了。

我们可以这样理解: NSNotificationCenter就是一个信息中心,有很多用户已经声明他们需要这些信息。当有信息更新的时候,通过这个 NSNotificationCenter就可以以广播的形式,将信息更新的消息在整个应用程序中间广播,对于那些注册消息侦听的用户就可以受到该消息,没有注册的用户就无法接收该消息。

用法:

1. 定义一个方法
当注册信息侦听的对象,接受到消息后就调用该函数作为消息相应的函数。
-(void) update (NSNotification*)notification

{

    NSString* str = (NSString*)[notification object];//这里取出刚刚从过来的字符串


2. 对象注册,并关连消息
实质上也就是注册事件的侦听,
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update) name:
@"updateMessage"

    object:nil ]

3. 在要发出通知消息的地方

[[NSNotificationCenter defaultCenter] postNotificationName:
@" updateMessage"

      object: @"ShowHomeLineViewController"/*传的参数,多个参数就可以用数组啦*/];

4:使用完后,别忘了注销掉该消息的侦听函数

不要忘记移除监听

[[NSNotificationCenter defaultCenter] removeObserver:self  name:@" updateMessage" object:nil];

THE END !

2011-07-12