带Block的NSNotification注意正确移除观察者的方

2018-12-08  本文已影响0人  Leon1024

NSNotification 的 observer 有两种类型:
一种是不带block的,这类观察者iOS9.0后无需手动移除


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

一种是带block的,这类观察者必须手动移除。而且这类观察者是和创建它的类(self)没有任何关联的。这类观察者只会强引用(持有)它的block。这类观察者如果不移除,会每个观察者都持有一个block。如果接收到通知,多个观察者都会调用该block。造成重复调用。所以,一定要用正确的姿势去移除该类观察者。首先是要将方法返回的观察者引用起来供移除的时候使用。如下是正确的操作方式:

 #import "ObserverVC.h"

@interface ObserverVC ()
@property (nonatomic, strong) id obser;
@end

@implementation ObserverVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
   // 这里一定要把返回的观察者引用起来,移除观察者的时候使用
    self.obser = [[NSNotificationCenter defaultCenter] addObserverForName:@"TestNotification" 
                                                         object:nil queue:[[NSOperationQueue alloc] init] 
                                                               usingBlock:^(NSNotification * _Nonnull note) {

       NSLog(@">>>>收到通知>>>>");

    }];
}

- (void)dealloc
{
    // 将引用起来的观察者移除,只有这种方式才能正确移除这类观察者.
    [[NSNotificationCenter defaultCenter] removeObserver:self.obser];
    
}


@end
上一篇下一篇

猜你喜欢

热点阅读