ios - 在 ARC 上创建 IBOutlets 作为 ivars。内存问题?

标签 ios objective-c memory properties ivars

我知道 Objective-C 开发的最佳实践表明 IBOutlets 应始终根据 Apple 定义为属性。

From a practical perspective, in iOS and OS X outlets should be defined as declared properties. Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong.



但出于学习目的,假设我们使用 ARC 得到了以下场景:
#import <UIKit/UIKit.h>

@interface DetailViewController : UIViewController{
     IBOutlet UIButton *buttonA;
     IBOutlet UIButton *buttonB;
     IBOutlet UIButton *buttonC;
}

@end

如果我没记错的话,这三个按钮很强大,所以我的问题是:一旦释放 ViewController,这些按钮会从内存中释放吗?

如果它们很弱,这些按钮会自动释放,我知道,但不确定它们是否强大。

有人可以帮忙吗?为了清楚起见,DetailViewController 上的方法 'dealloc' 是空的。

最佳答案

您询问:

If I'm not mistaken, those three buttons are strong, so my question is: Will those buttons be released from memory once the ViewController is released?



是的。或者,更准确地说,当没有更多的强引用时,这些按钮将被释放。在这种情况下,这些按钮现在有两个 strong引用,一个是 View Controller ,另一个是这些按钮作为 subview 添加到的 View 。这两个strong在释放按钮之前需要解除引用。

但是为什么要维护对该控件的两个强引用呢?通常你让 View 保持strong引用其 subview (即让 View “拥有”其 subview ),并且 View Controller 仅使用 weak引用这些 subview 。

Those buttons would be released automatically if they were weak, I know that, but not sure if they are strong.



当 View Controller 有 weak引用,按钮被释放是因为唯一的 strong对按钮的引用由其父 View 维护,当该 View 被删除时,按钮将失去其最后一个强引用并且可以被释放。

如果 View Controller 有 strong引用,你被不必要地添加了另一个 strong在释放按钮之前需要释放的引用。你可以这样做,但这是不必要的。您引用了 Resource Programming Guide ,但前面的句子说“你不需要对图中较低的对象进行强引用,因为它们归其父级所有,你应该尽量减少创建强引用循环的风险。”

底线,你的例子隐含 strongIBOutlet 的引用控件将正常工作。但是让 View Controller 维护 strong 没有任何好处。对按钮的引用,它代表了对对象图的一些误解。 View Controller 真的应该只维护 weak对他们 View 上的控件的引用。

关于ios - 在 ARC 上创建 IBOutlets 作为 ivars。内存问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20442351/

相关文章:

ios - 在滚动幻灯片中的每个 UICollectionViewCell 中弄乱 UIButton

ios - 使用自动布局以编程方式将自定义 UIView 居中

iphone - 如何知道应用程序是否已预先安装在 iOS 设备上?

c - 为传递给函数的数组指针初始化内存时出现段错误

ios - NSUbiquitousKeyValueStore 不与 iCloud 同步

ios - 通用 UIPopoverPresentationController 代码

objective-c - 在源列表中显示固定和可编辑的项目

ios - WatchKit 如何处理图像?

c# - TiffBitmapEncoder,内存错误导致 C#/WPF 中内存不足异常

ios - 可调整大小的居中圆形 UIView