ARC:何时将viewController设置为nil

时间:2012-03-13 10:15:41

标签: iphone objective-c ios5 automatic-ref-counting

我还在为ARC的想法苦苦挣扎。假设我有两个非常复杂的viewControllers A和B,每个都包含很多图片,每个图片都保留在每个视图中。为了论证,我们假设第一个ViewController(A)保留了RAM中占用75 MB的图像。另一个(B)也占用了75 MB。

在我的App Delegate中,我设置了我的NavigationController,如下所示:

ViewControllerA *vcA = [[ViewControllerA alloc] init];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:vcA];
[navController.navigationBar setHidden:YES];
[[self window] setRootViewController:navController];

当我从A切换到B时,我在ViewControllerA.m中这样做:

ViewControllerB *vcB = [[ViewControllerB alloc] init];
[[self navigationController] pushViewController:vcB animated:YES];

当我切换回来时,我在ViewControllerB.m中这样做:

[[self navigationController] popToRootViewControllerAnimated:YES];

现在我的一个大问题是,当我在ViewController B中时,我的内存中是否还有ViewController A?在这种情况下,编译器什么时候发布ViewController?我可以或不应该在不使用时释放(即将其设置为nil)一个ViewController吗?

如果答案很清楚或者我完全忽略了这一点,我很抱歉。因此,任何答案和解释都将受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

是的,您仍然拥有ViewControllerA(您可以在下次使用Instruments查看)。这与ARC无关,没有它也是如此。让我解释一下:

你创建一个UINavigationController并将UIViewController A作为根,保留A(在ARC中它是一个强大的属性或类似的东西),你可以看到UINavigationController需要它吗? 现在你按UIViewController B,B和A存在于内存中,你UINavigationController仍然需要UIViewController A,它只是没有显示并且视图可以被卸载,如果系统需要内存,但是它不会释放A.当你弹出UIViewController B时,它被释放,如果没有它的引用(再次,我认为这是ARC工作的方式)它被解除分配。

现在你的问题是,什么时候rootViewController被解除了?好吧,UINavigationController 总是有根!所以,当你有一个UINavigationController时,你有一个rootViewController。

如果您需要进一步解释,请在评论中告诉我。

答案 1 :(得分:1)

我无法帮助你使用ARC,因为我从未使用它(我不知道我是否真的想要)。

但我可以告诉你一件事:

推送ViewControllers时,它们都在导航堆栈中。直到它们在堆叠中,它们仍留在记忆中。

如果我不使用ARC,如果我自动释放eatch viewController我会推送,它会在我从堆栈弹出时准确释放。

如果有人了解更多关于ARC的信息(当它发布分配的对象时),我很乐意获得更多信息。

由于