NSNotification

224 阅读1分钟
  • 添加监听

    - (void)addObserver:(id)observer selector:(SEL)aSelector 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 API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.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.
    
    1. 如果NSNotificationName为nil,则会接收所有的通知

    2. 监听同一条通知的多个观察者,在通知到达时,它们执行回调的顺序是不确定的

    3. 如果queue为nil,则消息是默认在post线程中同步处理,即通知的post与转发是在同一线程中

    4. block块会被通知中心拷贝一份(执行copy操作),以在堆中维护一个block对象,直到观察者被从通知中心中移除。所以,应该特别注意在block中使用外部对象,避免出现对象的循环引用

    5. 每次调用addObserver时,都会在通知中心重新注册一次,即使是同一对象监听同一个消息,而不是去覆盖原来的监听。当通知中心转发某一消息时,如果同一对象多次注册了这个通知的观察者,则会收到多个通知。

    6. 通知的发送与处理是同步的,在某个地方post一个消息时,会等到所有观察者对象执行完处理操作后,才回到post的地方,继续执行后面的代码。

    7. 使用block的通知,一定要移除通知

    @property (nonatomic, weak) id observer;
    
    self.observer = [[NSNotificationCenter defaultCenter]addObserverForName:@"note" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
    }];
    
    // 移除通知
    [[NSNotificationCenter defaultCenter]removeObserver:self.observer];