gpt4 book ai didi

ios - 内存未在 ios View 层次结构中释放

转载 作者:可可西里 更新时间:2023-11-01 05:38:33 25 4
gpt4 key购买 nike

我有一个使用 ARC 的 iOS 应用程序。我不使用 InterfaceBuilder,所有 UI 都是手动生成的。在那个应用程序中,我有几个 UIViewControllers 和 SubViewControllers。这些 ViewControllers 从一个菜单 (-ViewController) 捆绑在一起,菜单将它们推送到堆栈上。

我的问题是,在 ViewController 之间切换时没有释放内存。

像这样保留对 SubViewController 的引用是错误的吗?

@property (nonatomic, strong) UIViewController subViewController1; 
@property (nonatomic, strong) UIViewController subViewController2;

viewDidUnload 永远不会被调用。谁有一个很好的例子来说明如何构建一个干净的 View 层次结构?

最佳答案

通过将压入堆栈的 View Controller 分配给强实例变量/属性,它们在从堆栈弹出时不会被释放。强大的属性即使在它们从堆栈中弹出后也会保留在推送的 View Controller 上,因此它们永远不会达到可以释放的状态。

通常我会在将下一级 View Controller 推送到导航堆栈时执行如下操作:

SLSMoleculeSearchViewController *searchViewController = [[SLSMoleculeSearchViewController alloc] initWithStyle:UITableViewStylePlain];
[self.navigationController pushViewController:searchViewController animated:YES];

在 ARC 下,新的 View Controller 将被分配并在创建时保留。当推送到导航堆栈时,它将被导航 Controller 保留一次。因为这个新的view controller在push之后没有被引用,也没有赋值给strong property或者instance variable,所以ARC会在第二行之后释放它。

请记住,它仍然由导航 Controller 保留,所以它仍然存在于内存中。但是,一旦导航 Controller 将其从堆栈中弹出,该 View Controller 就会被释放。由于此时没有任何东西保留它,因此它将按预期被释放。

如果出于某种原因您需要在更高级别的 View Controller 中维护对此 subview Controller 的引用,您可以使用 weak 属性或 __weak 实例变量.这不会保留在 View Controller 上,一旦 Controller 被释放,它就会变为 nil。

weak 引用仅支持面向 iOS 5.0 的应用程序,因此您无法对需要在 iOS 4.0 上运行的任何应用程序执行此操作。与 4.0 兼容的 unsafe_unretained 属性不是我在这种情况下推荐的东西,因为指向释放内存的指针存在危险。

关于ios - 内存未在 ios View 层次结构中释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8747942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com