开发者

What's a good place to unregister an observer from the notification center?

开发者 https://www.devze.com 2022-12-27 07:54 出处:网络
When I add an observer to the default notification center, where would I unregister that? Example: I have a UIView subclass which lives i开发者_如何学Gonside a view controller. That subclass is an ob

When I add an observer to the default notification center, where would I unregister that?

Example: I have a UIView subclass which lives i开发者_如何学Gonside a view controller. That subclass is an observer for the FooBarNotification. If this notification is posted, that view will get it. But now, the view controller decides to throw away the view. Is the best place the -dealloc method of the view itself?

Are there any rules like memory management rules? For example: Must I unregister an observer where I registered it? i.e. the view registers itself in it's init method, so it should unregister itself in it's -dealloc method?

(not talking about push notifications, but NSNotificationCenter)


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

Since -addObserver:… will not -retain the observer, if the registration outlives the observer itself, your program will crash.

Apple doesn't specify any rules to unregister the observer. -dealloc is fine. Just use common sense. E.g. if that observer may persist even after the view controller throw it away, then you should unregister at that throw-away procedure, otherwise the observer may receive unwanted notifications.


Certainly it should be done in the dealloc, but basically when you no longer need notifications.

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

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


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

This works because almost always I won't want a notification to be picked up by a view that isn't currently in the foreground (any longer living observers I register in my coordinator)


Dealloc and viewDidUnload if you have registered for notifications in viewDidLoad.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号