关于iPhone当中viewdidunload和dealloc的调用时机

本文探讨了基于UINavigationController的应用中遇到的内存管理问题,详细分析了ViewController在不同生命周期方法中的调用情况,特别是在内存警告下的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近的一个项目, 基于UINavigationController, 发现个奇怪的问题, 从ViewController (A) push 到ViewController (B) 之后, 发现内存有所增加, 再点左上角的返回按钮回到(A)后, 内存一直在增加, nslog之后发现(B)的viewDidUnload方法根本没有调用, 更别说dealloc, 但viewDidDisappear还是调用了的. google了一番, 终于找到答案: 
http://stackoverflow.com/questions/5594410/viewdidunload-is-not-getting-called-at-all
  1. As others have mentioned, viewDidUnload is a method of UIViewController. It isn't guaranteed to get called. It only gets called in low memory situations when the app releases the controller's view to free up memory. This gives you an opportunity to release any of the view's subviews that you may have retained as properties of your controller.
  2. If you're calling removeFromSuperview on your view controller's view, then you're probably using UIViewController in a context it wasn't designed to handle. View controllers are designed to manage full-screen views. These views are expected to be presented in just a handful of contexts on the iPhone:
  3. As the full-screen view of the window's root view controller
  4. As a full screen view in a hierarchy of screens managed by UINavigationController
  5. As a full screen view presented within a tab
  6. As a full screen view presented using presentModalViewController:animated:
  7. As long as you're using the view controller in these contexts (plus a couple other contexts on iPad), then you can reliably manage your view's life-cycle via the loadView, viewDidLoad, viewWillAppear:animated:, viewDidAppear:animated:, viewWillDisappear:animated:, and viewDidDisappear:animated:, and viewDidUnload methods (again, bearing in mind that viewDidUnload won't always get called).
  8. The only time you should typically pass a view controller's view to addSubview: is when you add your root view controller's view to the window. If you want to try to use a nested view controller to manage a non-fullscreen subview, you'll have to call its viewWill/DidAppear/Disappear:animated: and viewDidUnload methods manually at appropriate times from your full-screen view's controller.
  1. Interface Builder caches nibs until there's a memory warning, or it exhausts its cache. At such time, it will reclaim any memory that it was using.

于是模拟了一下内存警告, 发现(B)的viewDidUnload方法确实立即被调用了, 如何我push, pop这样来回多次, 当模拟内存警告后, (B)的viewDidUnload方法也会被调用多次, 然而dealloc却还是没有调用. (稍后研究)

转载于:https://www.cnblogs.com/zsw-1993/archive/2013/03/06/4880330.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值