Daily Archives: 2012 年 07 月 03 日

Hello World

NSNotificationCenter 的使用

1. 定义一个方法

      -(void) update{       
             //...
      }

2. 对象注册,并关连消息

     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update) name:@"gotoupdate" object:nil]

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

     [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoupdate" object:nil];

每个运行中的application都有一个NSNotificationCenter的成员变量,它的功能就类似公共栏. 对象注册关注某个确定的notification(如果有人捡到一只小狗,就去告诉我). 我们把这些注册对象叫做 observer. 其它的一些对象会给center发送notifications(我捡到了一只小狗). center将该notifications转发给所有注册对该notification感兴趣的对象. 我们把这些发送notification的对象叫做 poster
Notification 就是设计模 式中的 观察者模式, cocoa为我们实现了该模式


———————————
2012.7.11

刚发现一个严重的问题,如果使用addObserver多次注册同一个方法,再通过postNotificationName调去方法,这个方法会被执行多次!
解决的方法,是在方法调用以后,通过removeObserver方法解除注册

     -(void) update{
          [[NSNotificationCenter defaultCenter]removeObserver:self name:@"gotoupdate" object:nil];
          //...
     }