简体   繁体   中英

Where should I put removeObserver from NSNotification

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM