1

我是 Objective-C 的新手。这是我对一些用于以编程方式添加子视图的简单代码的 ARC 的理解(如在评论中)。如果我错了,请纠正我。特别是在这个声明中:

“ViewController 弱指向 myView”实际上意味着 _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. 
4

1 回答 1

3

你大部分是正确的,除了这句话:

viewDidLoad 完成后, mv 被释放。

那就是你错了。请记住,对象的释放只有retain在对象release的每个人都属于它时才会发生。因此,虽然您已经获得release了临时变量mv,但您仍然有另一个来源保留它:self.view.subviews. 一旦mv从子视图数组中删除,它就可以被正确清理,_myView设置为nil,并且您不再有泄漏。

于 2012-08-30T12:45:57.523 回答