NSNotificationCenter实质上就是一种观察者模式,让不同的对象之间实现通信,要注意的是:NSNotificationCenter只允许同⼀一个程序中的不同对象之间进⾏行通信,它们不能跨越不同的应⽤。
这种模式耦合度较松(delegate的耦合度较高)。
示意图:
NSNotificationCenter就是一个消息中心,首先是由观察者(observer)所在的对象向NSNotificationCenter进行注册。
注册方法:
首先调用一个类方法(defaultCenter,单例模式),然后调用实例化方法addObserver:
-addObserver:selector:name:object:
该⽅方法第⼀个参数为监听者,第二个参数selector参数⽤于指定监听者的监听方法,第三个参数name指定通知名称,第四个参数object代表发送者对象(poster),如果object参数为nil,则代表⽤用于监听任何对象发出的通知
在没有对象发送NSNotification时,这些观察者都静止的,当有一个对象发送了NSNotification,所有注册过的,名称相对应的观察者(observer)都会激发。
iOS SDK中很多对象都会发送NSNotification
•当应⽤程序状态改变时,UIApplication会对外发送NSNotification
• 当键盘出现时,UIWindow会对外发送NSNotification
• 当UITableView选中⾏发⽣变化时,UITableView会对外发送NSNotification
等等。。。。。。
可以查看UIKit的API⽂文档,专⻔有一个分类列出该组件可能发出的NSNotification 。
除了注册方法,还有两种方法:
•-removeObserver:name:object:删除监听者,删除对指定监听者(通过name参数指定)、指定通知的监听
•-postNotificationName:object:发送通知,该⽅法第⼀个参数指定通知名称,第⼆个参数指定通知的object
我们既可以使⽤用NSNotificationCenter监听⾃自定义通知,也可以使⽤用NSNotificationCenter监听系统组件的通知
用NSNotificationCenter监听⾃自定义通知:
•新建2个视图控制器类ViewController1、ViewController2
ViewController1中:
ViewController2中:
使⽤用NSNotificationCenter监听系统组件的通知 :
系统组件会在发⽣特定改变时发送通知,可以直接使⽤NSNotificationCenter监听系统组件的通知。监听系统组件的通知只要通过NSNotificationCenter注册监听者