5

Is it OK to use -removeObserver: first and then call -addObserver: with the same name? Or is it a rule to have -addObserver: first before -removeObserver:?

I tried it using OS 4.0 and it seems OK (no crash, warnings... etc.).

-(void) setObserver
{
[[NSNotificationCenter defaultCenter] removeObserver:self 
                                                name:OBSERVER_NAME object:nil]; 

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector: @selector(selectorName)
                                             name:OBSERVER_NAME 
                                           object:nil]; 
}

The reason is to prevent two observers with the same selectorName method being called twice assuming that -setObserver method was called again if its inside -viewDidLoad and a memory warning was issued.

Also, do I need to invoke -removeObserver: during -dealloc?

Chris Hanson
  • 54,380
  • 8
  • 73
  • 102
mark
  • 51
  • 1
  • 2
  • +1 good question. I dont' know if it's save to remove an Observer that was not registered before, but I know it's a must to remove the observer before deallocing. For your given case you could also remove the observer in viewDidUnload. That's what this method is for: Balancing all calls made in loadView and viewDidLoad. – tonklon Jul 07 '10 at 13:32

1 Answers1

3

If you're getting -selectorName invoked twice, there's probably some other issue with your code. And even if Cocoa will be graceful about removing observers you haven't added yet, I wouldn't actually do that.

As user tonklon says in a comment, you should probably remove the observer in -viewDidUnload. As to your last question, it's also reasonable to remove the observer in -dealloc, though it's good practice to structure your code such that things like removing observers happen at a deterministic time rather than as a side-effect of memory management.

Chris Hanson
  • 54,380
  • 8
  • 73
  • 102