[英]Objective-C: understanding ARC
我是Objective-C的新手。 以下是关于ARC的一些简单代码的理解(如在注释中),用于以编程方式添加子视图。 如果我错了,请纠正我。 特别是在这个声明上:
“ViewController弱点指向myView”ACTUALLY意味着_myView(ViewController的ivar)弱指向UIView对象
// _myView stores a pointer pointing to a UIView object
// "ViewController points to myView weakly" ACTUALLY means that _myView (ViewController's ivar) points to a UIView object weakly
@interface ViewController ()
@property (nonatomic,weak) UIView *myView;
@end
@implementation
@synthesize myView = _myView;
@end
- (void)viewDidLoad
{
[superviewDidLoad];
CGRect viewRect = CGRectMake(10, 10, 100, 100);
// a UIView object is alloc/inited
// mv is a pointer pointing to the UIView object strongly (hence the owner of it)
UIView *mv = [[UIView alloc] initWithFrame:viewRect];
// _myView points to the UIView object weakly
// Now the UIView object now have two pointers pointing to it
// mv points to it strongly
// _myView points to it weakly, hence NOT a owner
self.myView = mv;
// self.view points to the UIView object strongly
// Now UIView object now have THREE pointer pointing to it
// Two strong and one weak
[self.view addSubview:self.myView];
}
// After viewDidLoad is finished, mv is decallocated.
// Now UIView object now have two pointer pointing to it. self.view points to it strongly hence the owner, while _myView points to it weakly.
你大多是正确的,除了这句话:
viewDidLoad完成后,mv被解除分配。
那就是你错了。 请记住,只有当retain
对象的每个人release
它时,才会发生对象的release
。 因此,当您release
临时变量mv
,您仍然有另一个来源保留它: self.view.subviews
。 一旦从子视图数组中删除mv
,就可以正确清理它,将_myView
设置为nil
,并且不再有泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.