iphonecocoanotificationsaddobserver

Possible locations to call addObserver and removeObserver methods


I have a case where the child view sends notification to its parent view. Now I'm calling addObserver: in viewWillAppear: and removeObserver: in viewWillDisappear:. But, I'm guessing this is not correct since viewWillAppear: calls when view is refreshed.

[[NSNotificationCenter defaultCenter] addObserver: (id)observer selector: (SEL)aSelector name: (NSString *)aName object: (id)anObject];

[[NSNotificationCenter defaultCenter] removeObserver: (id)observer name: (NSString *)aName object: (id)anObject];

Thanks.


Solution

  • Actually, this is a bad idea. When memory gets low, your view controller may get sent a memory warning. The default behavior in this instance is to clear out your view (if you're not currently on screen). In this case, you could get the viewDidLoad message sent a second time (after the memory event, when your view is brought back on screen by its navigation controller.) Thus you'll have two registrations of the same object, but only one removal (in its dealloc)

    A better solution is either to set a flag saying you've registered, or to register in your init method.