使用addObserverForName时删除Observer:usingBlock

我有以下代码在视图加载中添加一个观察者。

- (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserverForName:@"com.app.livedata.jsonupdated" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notif) { NSLog(@"JSONUPDATED"); }]; } 

这很好。 但是当卸载视图并确认调用dealloc时,Notification仍在触发。

似乎没有一种方法可以停用这个观察者?

似乎解决方案是在视图中跟踪对象,然后您可以在dealloc方法中引用它。

  id observer = [[NSNotificationCenter defaultCenter] addObserverForName: /* ... */ ]; 

然后删除如下:

 [[NSNotificationCenter defaultCenter] removeObserver:observer]; observer = nil;