Remove Observer when using addObserverForName:usingBlock
Asked Answered
C

1

17

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?

Claireclairobscure answered 17/1, 2012 at 7:50 Comment(0)
C
32

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;
Claireclairobscure answered 17/1, 2012 at 8:27 Comment(1)
this one does not work if have same observers in 2 different classes and the observer never gets removed :/Barbarous

© 2022 - 2024 — McMap. All rights reserved.