关于正确移除addObserverForName 的姿势

[NSNotificationCenter defaultCenter] addObserverForName:这个方法我们一般用收听通知, 这个方法有Block的写法, 代码的可读比使用[NSNotificationCenter defaultCenter] addObserver更高, 所以我经常使用这个作为接听通知.

如果你在收听完了之后没有将它移出, 那么当你下一次再次调用这个通知后的时候, 收听通知就会执行2次block里面代码, 如果收听多次而没有移除收听的方法, 那么block里面的代码会被多次执行.

同样ViewController将一直不会调用- (void) deallloc这个方法.

下面示例一个监听通知的方法:

@interface()
@property (nonamic, strong) id observer;
@end
- (void) viewDidLoad {
    self.observer = [[NSNotificationCenter defaultCenter] 
    addObserverForName:MPMoviePlayerPlaybackDidFinishNotification
    object:nil 
    queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
}];
}

- (void) dealloc {
 [[NSNotificationCenter defaultCenter] removeObserver:self.observer];
  self.observer = nil;
}

记住一点要在最后把收听设置为nil, 否则这个收听一致不会被移除..

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容