objective-c – 在UIViewController的viewDidUnload中释放IBOutlets?

前端之家收集整理的这篇文章主要介绍了objective-c – 在UIViewController的viewDidUnload中释放IBOutlets?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我对基于Nib的UIViewControllers中究竟发生了什么感到困惑.生成UIViewController子类时,模板在viewDidUnload方法中包含一个非常具体的注释:
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;

这适用于哪些子视图?

>我在viewDidLoad中初始化的那些? (我会说是的)
>我在initWithNibName中初始化的那些? (我会说不)
>引用笔尖中的对象的IBOutlets?

如果我像这样使用视图控制器:

MyViewController *controller = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
[self.navigationController pushViewController:controller animated:YES];
[controller release];

在这种情况下,我认为持有对subview的引用的实例变量是否在viewDidUnload或dealloc中释放并不重要,因为一旦视图控制器从堆栈中弹出就会调用dealloc,所以我不如Apple所说的那样做并在viewDidUnload而不是dealloc上释放实例变量.

但是假设我使用MyViewController作为可以多次推送的实例变量:

if(self.myViewController == nil) {
    self.myViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
}
//Change some state which should be reflected in the view
self.myViewController.someProperty = someValue;
[self.navigationController pushViewController:self.myViewController animated:YES];

如果我在viewDidUnload中发布IBOutlet,会在MyViewController中发生什么?我可以指望在下一个viewDidLoad上有一个新的引用吗?

换句话说:viewDidUnload之后视图本身会发生什么?如果再次按下控制器,是否从Nib释放并重新加载?或者视图是否留在内存中?如果是这样,在viewDidLoad之前是否重新设置了出口?

如果视图保留在内存中并且在viewDidLoad之前重新设置了出口,或者每次按下控制器时重新加载出口,我认为在viewDidUnload中释放出口是正确的(即使在第一种情况下无关紧要) .但除此之外(特别是如果视图保留在内存中并且未重置插件),在viewDidUnload中释放子视图对于我提供的用例是错误的,我是否正确?

解决方法

UIViewController documentation,内存管理部分:

When a low-memory warning occurs,the UIViewController class purges its views if it knows it can reload or recreate them again later. If this happens,it also calls the viewDidUnload method to give your code a chance to relinquish ownership of any objects that are associated with your view hierarchy,including objects loaded with the nib file,objects created in your viewDidLoad method,and objects created lazily at runtime and added to the view hierarchy. Typically,if your view controller contains outlets (properties or raw variables that contain the IBOutlet keyword),you should use the viewDidUnload method to relinquish ownership of those outlets or any other view-related data that you no longer need.

因此,您不仅可以在viewDidUnload中释放您的插座,这是首选和推荐的方式.

是的,当调用viewDidLoad时,您可以指望您的出口指向有效对象.再次从UIViewController文档中,在viewDidLoad上:

This method is called after the view controller has loaded its associated views into memory.

原文链接:https://www.f2er.com/c/118035.html

猜你在找的C&C++相关文章