What is a good place to register an observer at the notification center?

When I add a watcher to the default notification center, where should I unregister?

Example: I have a UIView subclass that lives inside a view controller. This subclass is a watcher for FooBarNotification. If this notice is posted, this submission will receive it. But now the view controller decides to discard the view. Is it best to use the -dealloc method of the view itself?

Are there any rules like memory management rules? For example: Should I unregister the observer where I registered it? those. the view is registered in it by the init method, so should it unregister the -dealloc-method in it?

(not to mention push notifications, but NSNotificationCenter)

+2


a source to share


4 answers


The only rule is to make sure that the observer lives longer than the registration period.

Since there -addObserver:…

will be no -retain

observer, if the registration outlives the observer itself, your program will crash.



Apple does not specify any policy for observer deregistration. -dealloc

excellent. Just use common sense. For instance. if this observer can persist even after the view manager throws it, then you must unregister in this throwing routine, otherwise the observer may receive unwanted notifications.

+3


a source


Of course this should be done in dealloc, but mostly when you no longer need notifications.

One possible place is to override the willMoveToWindow: message on a UIView and remove the notification when the view is removed from the window:



- (void)willMoveToWindow:(UIWindow *)newWindow
{
    if (window == nil) {
        // view removed from a window -- remove notifications here
    }
    [super willMoveToWindow:newWindow];
}

      

+2


a source


I usually add my observers to viewWillAppear and remove them again in viewWillDisappear.

This works because almost always I don't want the notification to be picked up by a view that is not currently in the foreground (any more live observers I register with my coordinator)

+2


a source


Dealloc and viewDidUnload if you've registered for notifications in viewDidLoad.

0


a source







All Articles