views:

1958

answers:

3

I have a case where the child view sends notification to parent view. Now i'm calling addObserver in viewWillAppear and remove Observer 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.

A: 

I guess the correct positions to register for notification is viewDidLoad method, and correct position to unregister for same notifications is dealloc method.

Thanks.

Mustafa
+2  A: 

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.

Ben Gottlieb
A: 

Isn't viewWillAppear method called in that case? - when the view is brought back on screen by its navigation controller.

Mustafa