notification不移依然不会崩溃,原理是啥?

1,564 阅读1分钟

先梳理一下相应的api:

    在viewcontrollerdidload里这么写:
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"test"  object:nil];
    dealloc 里remove self

系统有一个通知中心,通知中心会记录观察者的地址,当有通知时,去通知对应的观察者,如果通知来时,观察者已经不在,理论上会引起野指针的crash。 在iOS9 之前是这样的,开发者需要自己移除,但是看苹果文档里的说明:

可以看到iOS9 之后不用移除了,这是为什么呢,系统做了什么操作,大胆猜测一下,应该是系统帮我们移除了,我们验证一下: 新建一个NSNotificationCenter 的分类,重写 //类别中的方法会覆盖本类中的方法。

- (void)removeObserver:(id)observer
{
    NSLog(@ "====%@--%@ remove===" , [observer class],observer);
}

我们在分类中重写了系统的方法,会覆盖掉系统的方法,然后我们进行测试, 在Aviewcontroller里

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notifycationMehod) name:@"testNotifycation" object:nil];
    // Do any additional setup after loading the view from its nib.
}
- (void)notifycationMehod{
    NSLog(@"TwoViewController receive notify");
}
- (void)dealloc{
    NSLog(@"AViewController dealloc");
}
// Do any additional setup after loading the view from its nib.
}

然后pop看打印

分类里方法果然被调用了,原来系统真帮我们移除了,这里也证明,系统也没有对这个observer弱引用,因为弱引用的话,就没必要这么做了,看其他博客,好像是一个unsafe_unretain的操作。