Where should I put removeObserver from NSNotification

310 views Asked by At

I have three viewControllers, and I'm trying to send a notification from viewController 3 to viewController 1 and 2. I think the best way to do this is to use NSNotification. Here's what I have so far:

In class C - Post the notification

[[NSNotificationCenter defaultCenter] postNotficationName:@"Updated "object:self];

In class B

In class A and B - Register first for the notification

// viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdate:) name:@"Updated" object:nil];

-(void)handleUpdate:(NSNotification *)notification {
    NSLog(@"recieved");
}

This works so far. But when I de-register it in class A and B:

- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

The handleUpdate method doesn't get called. So the obvious problem is when I removeObserver's for the notification.

My question is, if everything I did so far is correct, why isn't it working when I remove the removeObserver? If it's not correct, where can I removeObserver's?

1

There are 1 answers

3
Alex Cheng On BEST ANSWER

Everything you did is right. this is how the notification work. If your class A,B always need to handle the update, you won't removeObserver. Because you add your "addObserver" in viewDidLoad. it means you addObserver only once. The normal error is that you add "addObserver" in "viewWillAppear" or "viewDidAppear", it will add more than once observer in the class. Then, you have to removeObserver in viewDidDisappear.