学习IOS开发UI篇--NSNotificationCenter通知中心

  NSNotificationCenter 较之于 Delegate 可以实现更大的跨度的通信机制,可以为两个无引用关系的两个对象进行通信。NSNotificationCenter 的通信原理使用了观察者模式;

  1. NSNotificationCenter 注册观察者对某个事件(以字符串命名)感兴趣,及该事件触发时该执行的 Selector 或 Block

  2. NSNotificationCenter 在某个时机激发事件(以字符串命名)

  3. 观察者在收到感兴趣的事件时,执行相应的 Selector 或 Block

使用通知中心的步骤:

1.注册观察者

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

2.激发事件(发布广播)

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

3. 观察者会自动执行selector方法

4.当不想监听的时候取消监听(务必在对象销毁的同时进行)

一般在监听器销毁之前取消注册(如在监听器中加入下列代码):
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
原文地址:https://www.cnblogs.com/zhaoyan/p/3763817.html