Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 871
Mustafa Avatar asked Jan 01 '09 04:01

Mustafa


People also ask

Do I need to removeObserver?

addObserver in application, you don't have to call removeObserver , when the application is destroyed, the process would be killed also. If you call lifecycle.

What is notification observer in Swift?

Save. Notification Center use for broadcasting singles or notifying the methods at the same time. It uses the Observer pattern to inform registered observers when a notification comes in, using a central dispatcher called NotificationCenter.


1 Answers

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.

like image 58
Ben Gottlieb Avatar answered Nov 04 '22 14:11

Ben Gottlieb