在NSNotificationCenter调用.removeObserver的正确位置= Swift deinit()? [英] The right place to call .removeObserver for NSNotificationCenter = Swift deinit()?

查看:168
本文介绍了在NSNotificationCenter调用.removeObserver的正确位置= Swift deinit()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读了很多关于在正确的地方调用NSNotificationCenter的.removeObserver的建议,因为viewDidUnload不是一个选项.

I've read a lot of suggestions for the right place to call .removeObserver for NSNotificationCenter since viewDidUnload is not an option.

我只是想知道Swift中新的deinit()是否是一个不错的选择?

I was just wondering if the new deinit() in Swift would be a good choice?

-尼克

推荐答案

这实际上取决于您订阅NSNotificationCenter通知的类的角色.如果您订阅:

It really depends on the role of the class where you subscribe to NSNotificationCenter notifications. If you are subscribing in:

UIView

然后,您应该在用户看不到视图后立即取消订阅.为了节省CPU周期并在用户看不到视图时不占用资源.

Then you should unsubscribe as soon as view gets invisible to the user. To save CPU cycles and not consume resources while user does not see the view.

UIViewController

这还取决于您要响应通知执行的操作类型.如果只是UI调整,则应在视图控制器从屏幕上消失后立即退订.

Here it also depends on kind of action that you are going to perform in response to notification. If it is just a UI adjustment that you should unsubscribe as soon as view controller disappears from the screen.

您的App Service层

在deinit()中包含.removeObserver是可以的.但是,即使在这里,我还是建议您更加明确地说明何时订阅和取消订阅NSNotificationCenter通知,并将其置于服务的启动和停止方法中.

Here it is OK to have .removeObserver inside deinit(). however even here I tend to suggest you to be more explicit about when you subscribe and unsubscribe from NSNotificationCenternotifications and put them in start and stop methods of your service.

这篇关于在NSNotificationCenter调用.removeObserver的正确位置= Swift deinit()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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