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)
a source to share
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.
a source to share
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];
}
a source to share