iOS-开启arc之后 NSNotificationCenter removeObserver 是否需要调用

时间:2023-03-08 19:59:35
iOS-开启arc之后 NSNotificationCenter removeObserver 是否需要调用

开启ARC之后,NSNotificationCenter removeObserver 是否需要调用,在何时调用?

今天在*上面看到一个问题,arc情况下是否需要调用removeObserver,自己想了想,的确是个问题,就研究了一下。

上代码:

- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

本来想着在arc中dealloc方式是已经遗弃的了,但是事实是它还存在,但是不能像mrc中那样还需要调用一下[super dealloc],在arc环境下,这个方法是不能用的,否则编译器直接就报错。 
后来我就想到dealloc方式会正常调用吗?

下面是添加观察者的方法:

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

这个方法第一个参数Observer是不会对它进行retain操作,所以不会形成循环引用,但是还有必要调用removeObserver吗?

答案当然是:有必要!

如果这个对象被释放,当在调用post消息的时候,就会报对象被释放的错误,导致闪退,所以在添加观察者的对象,一定要在它被销毁的时候从消息中心删除!