iphone - ARC 下 -viewDidUnload 中的弱属性和强属性

标签 iphone objective-c xcode ipad automatic-ref-counting

我是 iPhone 开发的新手。我正在为我的项目使用 ARC。据我了解使用 ARC 我们不必手动释放任何对象。但是,我在某些地方观察到,即使在使用 ARC 之后,人们也会在 ViewDidUnload 中明确地将他们的对象设置为 nil。

例如,在 .h 文件中我有这样的内容:

@property (unsafe_unretained, nonatomic) IBOutlet MKMapView *mapViewOutlet;
@property (unsafe_unretained, nonatomic) IBOutlet UIToolbar *toolBar;
@property (strong,nonatomic) NSMutableArray *dataArray;

和.m如下:

- (void)viewDidUnload
{
     [self setMapViewOutlet:nil];
     [self setToolBar:nil];
     [super viewDidUnload];
     self.dataArray=nil;
}

我的问题是,即使在 ARC 下,是否真的有必要在 ViewDidUnload 中显式指定 nil?

最佳答案

viewDidUnload 方法的全部意义在于释放您并不真正需要的数据,以释放内存。阅读the documentation :

When a low-memory condition occurs and the current view controller’s views are not needed, the system may opt to remove those views from memory. This method is called after the view controller’s view has been released and is your chance to perform any final cleanup. If your view controller stores separate references to the view or its subviews, you should use this method to release those references. You can also use this method to remove references to any objects that you created to support the view but that are no longer needed now that the view is gone. You should not use this method to release user data or any other information that cannot be easily recreated.

所以您将属性设置为 nil现在释放对象并帮助系统释放一些内存。但这当然取决于属性类型——强属性是“你的”,只有你才能决定是否现在释放它们(通过设置为 nil)。弱属性可能已经是 nil,例如,如果它们指向一些与主视图一起发布的 View 。 unsafe_unretained 属性是一种特殊的野兽。它们指向的对象可能已经被释放,但这并不意味着它们被自动设置为 nil。因此,您应该使用其中一种“更安全”的属性类型(强/弱),或者在此处将不安全的属性设置为 nil,以确保您以后不会使用已释放的对象。在这种情况下没有硬性规定,您必须考虑具体情况及其对各种属性的意义。

顺便说一句,viewDidUnload 在 iOS 6 中被弃用,在低内存条件下不再释放 View 。您仍然会收到 didReceiveMemoryWarning 回调,以便您可以根据需要释放一些资源。同样,我建议您阅读文档并运行一些测试以查看会发生什么并决定您应该做什么。

关于iphone - ARC 下 -viewDidUnload 中的弱属性和强属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12104576/

相关文章:

iphone - 播放声音循环或停止使用AudioServices播放

iphone - 标签栏 Controller 下的导航 Controller 中的数组索引搞砸了

ios - 如何在 iOS 中轻松制作动画?

iphone - 核心数据的替代品

ios - 发现扩展时遇到 Swift 4 错误 - 照片无法在 UI 上加载

iphone - 在 Objective-C 中生成具有随机数长度的随机数

iphone - 解决多标签问题

ios - 分发证书自动吊销

xcode - SwiftUI 2.0 TabView 禁用滑动以更改页面

iphone - 如何在显示启动画面时从 Web 服务加载数据?