使用addObserverForName时删除Observer:usingBlock

Lee*_*ong 16 nsnotifications ios

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

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserverForName:@"com.app.livedata.jsonupdated"
                                                      object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notif) {
                                                          NSLog(@"JSONUPDATED");
                                                      }];
}
Run Code Online (Sandbox Code Playgroud)

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

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

Lee*_*ong 26

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

 id observer = [[NSNotificationCenter defaultCenter] addObserverForName: /* ... */ ];
Run Code Online (Sandbox Code Playgroud)

然后删除如下:

[[NSNotificationCenter defaultCenter] removeObserver:observer];
observer = nil;
Run Code Online (Sandbox Code Playgroud)