NSNotificationCenter 通知中心

来源:互联网 发布:北京java周末班 编辑:程序博客网 时间:2024/06/05 02:13

通常我们在iOS中发生什么事件时该做什么是由Delegate实现的,例如View加载完后会触发ViewDidload.苹果还为我们提供了另一种通知响应方式 那就是NSNotificationCenter
与Delegate比较 NSNotificationCenter可以实现更大跨度的通信机制 可以为两个无引用关系的两个对象进行通信。
NSNotitficationCenter的通信原理使用了观察者模式:

注册观察者:

    [[NSNotificationCenter defaultCenter] addObserver:self                                             selector:@selector(execute:)                                                 name:@\"NOTIFICATION_NAME\"                                               object:nil];

上面代码的意义为:观察者self 在收到名为@”NOTIFICATION_nNAME”的事件 时执行方法 @selector(execute:) 最后一个参数是表示会对那个发送者对象发出的事件作出响应,nil时表示接受所有发送者的事件 一般都为nil。

激发事件,即通知相应的观察者

 [[NSNotificationCenter defaultCenter] postNotificationName:@\"NOTIFICATION_NAME\"                                                    object:nil];

这里的 object 参数对应到方法 - (void)execute:(NSNotification *)notification 里的 notification.object, name 就是 notification.name。

代码到这里,方法 - (void)execute:(NSNotification *)notification 就会得到执行了。

最后,你的观察者如果对一些事件没兴趣了,应该从 NotificationCenter 中移除掉

 [[NSNotificationCenter defaultCenter] removeObserver:self name:@\"NOTIFICATION_NAME\"                                              object:test];//object 与注册时相同
0 0