我知道 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 arestrong
.
当 View Controller 有
weak
引用,按钮被释放是因为唯一的 strong
对按钮的引用由其父 View 维护,当该 View 被删除时,按钮将失去其最后一个强引用并且可以被释放。如果 View Controller 有
strong
引用,你被不必要地添加了另一个 strong
在释放按钮之前需要释放的引用。你可以这样做,但这是不必要的。您引用了 Resource Programming Guide ,但前面的句子说“你不需要对图中较低的对象进行强引用,因为它们归其父级所有,你应该尽量减少创建强引用循环的风险。”底线,你的例子隐含
strong
对 IBOutlet
的引用控件将正常工作。但是让 View Controller 维护 strong
没有任何好处。对按钮的引用,它代表了对对象图的一些误解。 View Controller 真的应该只维护 weak
对他们 View 上的控件的引用。
关于ios - 在 ARC 上创建 IBOutlets 作为 ivars。内存问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20442351/