在 UIViewController 中加载和卸载数据

发布于 2025-01-08 21:13:13 字数 1002 浏览 0 评论 0原文

我需要在 UIViewController 中加载一些数据,以在 iPhone 模式视图中显示 UIPickerView 小部件。

我做了一些研究,发现了这个答案。我继续在 initWithNibName:bundle: 中实现数据读取代码,并在 dealloc 中实现数据卸载。然而,Instruments 一直告诉我在重复显示模态视图时存在内存泄漏,并且在调试过程中我注意到每次显示视图时都会调用 initWithNibName:bundle: ,但在正常情况下从未调用 dealloc执行(尽管它是由低内存条件触发的,按照 Apple 的 UIViewController 类参考文档,以及同样适用于viewDidUnload)。

我最终在 viewDidLoad: 方法中加载数据,并在 viewDidDisappear: 中释放它,小部件显示了数据并且没有泄漏。但是,我想知道这方面是否有任何好的做法,因为苹果文档中的一条评论提到了这一点:

您不应该使用此方法(即viewDidUnload)来释放用户数据或任何其他无法轻松重新创建的信息。

我假设正确的方法是在 viewDidLoad 中加载数据并在 viewDidUnload 中释放对它的所有引用,但实际上,除非出现内存不足的情况,否则不会调用后一个方法,因此每次显示视图时,都会再次加载数据并且对旧数据的引用丢失,导致内存泄漏。

感谢您的评论。

I need to load some data in my UIViewController to show a UIPickerView widget in an iPhone modal view.

I did some research and found this answer in SO. I proceeded to implement my data reading code in initWithNibName:bundle: and data unloading in dealloc. However, Instruments kept telling me there was a memory leak when repeatedly showing the modal view, and during debugging I noticed initWithNibName:bundle: was called each time the view was shown, but dealloc was never called under normal execution (although it's triggered by a low-memory condition as per Apple's UIViewController Class Reference document, and the same applies to viewDidUnload).

I ended up loading data in the viewDidLoad: method and I released it in viewDidDisappear:, the widget shows the data and there are no leaks. However, I'd like to know if there are any good practices in regards to this, because on one comment in Apple's documentation mentions this:

You should not use this method (i.e. viewDidUnload) to release user data or any other information that cannot be easily recreated.

I assumed the right way was load data in viewDidLoad and releasing all references to it in viewDidUnload, but in practice the latter method is not called unless a low-memory condition arises, and consequently each time the view is displayed, the data is loaded again and the reference to the old data is lost, causing the memory leak.

Thanks for your comments.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

愁以何悠 2025-01-15 21:13:13

如果每次显示视图时都调用 viewDidLoad ,就会发生不好的事情。 viewDidAppear 应该被调用,但是 viewDidLoad 应该只在第一次需要视图时调用,并且如果需要视图并且 viewDidUnload 被调用。

Something bad is happening if viewDidLoad is getting called every time your view is shown. viewDidAppear should get called, but viewDidLoad should only be called the first time the view is needed and if the view is needed and viewDidUnload got called.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文