何时取消订阅UIView中的NSNotification [英] When to unsubscribe from a NSNotification in a UIView

查看:165
本文介绍了何时取消订阅UIView中的NSNotification的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在UIView中使用以下NSNotifications,以便在UIKeyboard显示时可以通知视图,并在屏幕上调整其位置(框架):

I am using the following NSNotifications within a UIView so that the view can be notified when a UIKeyboard appears and adjust its position (frame) on screen:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];

上述两个通知正在 -init 方法的UIView。视图在屏幕上消失后,最好从哪些位置取消订阅这些通知?目前,当UIKeyboard出现在另一个视图中时,应用程序崩溃,可能是因为通知仍然发送到当时发布的UIView。

The two notifications above are being subscribed to within the -init method of the UIView. Where is the best place to unsubscribe from these notifications once the view has disappeared off-screen? At the moment the app is crashing whenever the UIKeyboard appears in another view, presumably because a notification is still being sent to the then released UIView.

此外,除了在 -init 方法中订阅通知的地方吗?

Also, is there a better place to be subscribing to the notifications, apart from within the -init method?

感谢您的帮助。 / p>

Thanks for any assistance.

推荐答案

- [UIView willMoveToWindow:] - [UIView didMoveToWindow] ,即使从窗口中删除视图。窗口参数(或 -didMoveToWindow 的情况下的窗口属性)将为nil,在这种情况下,i。 e::

-[UIView willMoveToWindow:] and -[UIView didMoveToWindow] are called even when a view is removed from a window. The window argument (or the window property in the case of -didMoveToWindow) will be nil in that case, i. e.:

- (void)willMoveToWindow:(UIWindow *)newWindow {
    if (newWindow == nil) {
        // Will be removed from window, similar to -viewDidUnload.
        // Unsubscribe from any notifications here.
    }
}

- (void)didMoveToWindow {
    if (self.window) {
        // Added to a window, similar to -viewDidLoad.
        // Subscribe to notifications here.
    }
}

除了一些边缘情况,这是一种安全的方式去做吧。如果您需要更多的控制,您可以观察您的视图属于的窗口的隐藏属性。

Except for a few edge cases this is a safe way to do it. If you need more control, you can observe the hidden property of the window to which your view belong.

这篇关于何时取消订阅UIView中的NSNotification的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆