簡體   English   中英

Objective-C:理解ARC

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM