是否应在使用 ARC 时删除所有子视图



当用户在应用程序中移动时,我将UIViews堆叠在一起,在不同的屏幕之间来回移动。这些 UIView 可以是普通控件(按钮、标签等),也可以是从 UIView 继承的自定义控件。当按下其中一个屏幕上的后退按钮时,我执行了大量清理代码以释放实例变量的内存,以及停止计时器和关闭网络连接。我认为在这里使用 ARC 并部署到 iOS 6 和 iOS 7 设备也很重要。

一个典型的控件将像这样编码:

    UIImageView *ivSoundBottom = [[UIImageView alloc] initWithFrame:CGRectMake(270, 365, 30, 30)];
    UIImage *imgSoundBottom = [UIImage findCustomImage:@"ICN_Alarm_Sound_Bottom.png"];
    [ivSoundBottom setImage:imgSoundBottom];
    [self addSubview:ivSoundBottom];
    imgSoundBottom = nil;
    ivSoundBottom = nil;

此控件在屏幕加载时创建,并且永远不会再次引用。

我的问题是:在 ARC 下,我是否仍然需要遍历所有子视图并在每个子视图上调用 removeFromSuperview 来释放内存?

不,你没有。 您也不需要这些语句:

imgSoundBottom = nil;
ivSoundBottom = nil;

因为 ARC 将意识到对这些变量的引用超出了范围,并为您执行此操作。

最新更新