通知中心:实现了一对多的消息传递,可以实现跨页面传递。
cocoa消息机制算是同步的,观察者只要向消息中心注册,即可接受其他对象发送来的消息,消息发送者和消息接受者两者可以互相一无所知,完全解耦。这种消息机制可以用应用于任意时间和任何对象,观察者可以有多个。所以消息具有广播的性质,注意:观察者向消息中心注册以后,在不需要接受消息时需要向中心注销,属于典型的观察者模式。
消息通知中重要的两个类:
1)NSNotificationCenter:实现NSNotificationCenter的原理是一个观察者模式,获得NSNotificationCenter的方法只有一种,那就是[NSNotificationCenter defaultCenter],通过调用静态方法defaultCenter就可以获取这个通知中心的对象了。NSNotificationCenter 是一个单例模式,而这个通知中心的对象会一直存在于一个应用的生命周期。
2)NSNotification:这是消息携带的载体,通过它,可以把消息内容传递给观察者。
NSNotificationCenter的主要方法有以下几种:
@property (class, readonly, strong) NSNotificationCenter *defaultCenter;
- (void)addObserver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString *)notificationName object:(id)notificationSender
//。1.notificationObserver不能为nil
// 2.notificationSelector回调方法有且只有一个参数(NSNotifcation对象)。
//。3.监听同一条通知的多个观察者,在通知到达时,它们执行回调的顺序是不确定的,所以我们不能去假设操作的执行会按照添加观察者的顺序来执行。
- (void)postNotification:(NSNotification *)notification;
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject;
- (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject;
- (id <NSObject>)addObserverForName:(nullable NSNotificationName)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block NS_AVAILABLE(10_6, 4_0);
// The return value is retained by the system, and should be held onto by the caller in
// order to remove the observer with removeObserver: later, to stop observation.
其中最后一个方法返回NSObserver对象,在使用此方法添加观察者的时候,需要注意循环引用和remove的方式。每种方法都在不同系统上的表现也不尽相同。
一、添加observer的方法
1.SEL方式
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;
此方法中的observer是弱引用,直接使用self等不会造成强引用。