Remove Observer when using addObserverForName:usingBlock

巧了我就是萌 提交于 2019-12-22 01:42:38

问题


I have the following code that adds an observer in the loading of the view.

- (void)viewDidLoad
{
    [super viewDidLoad];

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

And this fires fine. However when the view is unloaded and I confirm the dealloc is called the Notification is still firing.

There doesn't seem to be a method for deactivating this observer?


回答1:


Seems the solution is to track the object in the View and then you can reference it in the dealloc methods.

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

And then remove as following:

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


来源:https://stackoverflow.com/questions/8891229/remove-observer-when-using-addobserverfornameusingblock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!