2009-08-09 28 views
1

我一直在嘗試一些來自Erica Sadun的書「iPhone Developer's Cookbook」的視圖代碼,並發現了一些我不明白的代碼。下面是一個的loadView方法的代碼:爲什麼iPhone Developer's Cookbook的這段代碼有效?

- (void)loadView 
{ 
    // Create the main view 
    UIView *contentView = [[UIView alloc] initWithFrame: 
     [[UIScreen mainScreen] applicationFrame]]; 
    contentView.backgroundColor = [UIColor whiteColor]; 
    self.view = contentView; 
    [contentView release]; 

    // Get the view bounds as our starting point 
    CGRect apprect = [contentView bounds]; 

    // Add each inset subview 
    UIView *subview = [[UIView alloc] 
     initWithFrame:CGRectInset(apprect, 32.0f, 32.0f)]; 
    subview.backgroundColor = [UIColor lightGrayColor]; 
    [contentView addSubview:subview]; 
    [subview release]; 
} 

我的問題是,爲什麼她釋放內容查看,但隨後在[contentView addSubview:subview]再次使用它?有self.view = contentView保留contentView?

+0

這看起來不對。 'contentView'不會在方法結束之前被釋放,所以這可能不會導致任何問題,但我無法想象爲什麼你會故意用這種方式構建它。 – kubi 2009-08-09 00:33:51

+0

不是。對self.view的賦值保留了contentView,所以在創建對象時最近可以得到它。這是故意構建的,因爲(在Cocoa範例中)視圖控制器保留視圖是有意義的。 – 2009-08-09 15:40:31

回答

7

如果你的UIViewController的文檔看,你會看到視圖屬性被聲明爲:

@property(nonatomic, retain) UIView *view;

這意味着,當您使用的setView:方法(或者在=的左邊使用.view),那麼你傳入的任何值都將被保留。所以,如果你通過代碼,並期待在保留數,你會得到這樣的:

- (void)loadView { 
    // Create the main view 
    UIView *contentView = [[UIView alloc] initWithFrame: 
      [[UIScreen mainScreen] applicationFrame]]; //retain count +1 
    contentView.backgroundColor = [UIColor whiteColor]; //retain count +1 
    self.view = contentView; //retain count +2 
    [contentView release]; //retain count +1 

    // Get the view bounds as our starting point 
    CGRect apprect = [contentView bounds]; 

    // Add each inset subview 
    UIView *subview = [[UIView alloc] 
      initWithFrame:CGRectInset(apprect, 32.0f, 32.0f)]; 
    subview.backgroundColor = [UIColor lightGrayColor]; 
    [contentView addSubview:subview]; 
    [subview release]; 

}

我想說的是,真正有趣的事情,那就是釋放內容查看後,我們仍然可以發送消息給它,因爲生活在contentView指針末尾的對象仍然存在(因爲它通過調用setView :)來保留)。

+1

這是正確的,但我個人避免這種風格/模式 - 如果在某個時候你決定改變該屬性從'retain'到'assign',那麼這段代碼將自發地開始崩潰。當然,這不是UIViewController.view屬性的問題,但是對於你自己的屬性,它要求在路上遇到麻煩。 – 2009-08-09 01:03:27

+1

是的,這正是它工作的原因,它是一種可怕的形式。一旦你釋放一個特定的參考,你不應該再次使用它,這是容易出錯的。該版本應該移動到最後,否則contentView的所有外觀應該更改爲self.view。 – 2009-08-09 02:47:48

+0

它並不真正符合風格,除非「認爲有害」是一種風格。 – Amagrammer 2009-08-09 04:23:57

0

如果你聲明你的屬性像這樣 @property(nonatomic,retain)... TheN yes屬性在分配時被保留。這可能是發生了什麼事情

+0

制定一個明確正確的答案並避免即時通訊式縮寫可能有助於避免將來降價。 (我沒有downvote,我只是說...) – 2009-08-09 15:44:24

+0

我知道,但從iPhone輸入響應很困難,當我寫出最低限度,並且不能很好地表達編碼時,但我認爲這個答案將有助於 的反正,所以我發佈它 – Daniel 2009-08-09 16:23:19