2012-04-11 14 views
2

看看我下面的代碼,我點擊「後退」按鈕後出現內存錯誤,如果我刪除,問題將被修復[aboutView release] 爲什麼?以及我應該如何發佈關於視圖?UIViewController動畫內存版本

-(IBAction)swichView { 
    AboutView *aboutView = [[AboutView alloc] init]; 
    [aboutView.view setAlpha:0]; 
    [self.view addSubview:aboutView.view]; 
    [UIView beginAnimations:@"" context:nil]; 
    [UIView setAnimationDuration:1.0]; 
    [aboutView.view setAlpha:1]; 
    [UIView commitAnimations]; 
    [aboutView release]; 
} 

第二個視圖Contorller:

-(IBAction)back { 
    [UIView beginAnimations:@"" context:nil]; 
    [UIView setAnimationDuration:1.0]; 
    [self.view setAlpha:0]; 
    [UIView commitAnimations]; 
    [self.view removeFromSuperview]; 
} 
+0

是否有一個原因,你添加'aboutView.view'而不是'aboutView'本身?崩潰的原因是'aboutView'不被保留。 – 2012-04-11 05:20:15

回答

0

在你switchView,你不應該產生的AboutView一個實例。 AboutView *aboutView應該創建爲實例變量,而不是函數局部變量。

由於視圖控制器動畫的設計,動畫本身不會NOT保留您的控制器並在動畫結束時自動釋放它。你的代碼在動畫期間釋放視圖控制器,這就是爲什麼它會崩潰。

要適當的釋放動畫後視圖,嘗試:

-(IBAction)switchView { 
    // given that aboutView is an instance variable 
    aboutView = [[AboutView alloc] init]; 
    [aboutView.view setAlpha:0]; 
    [self.view addSubview:aboutView.view]; 
    [UIView animationWithDuration:1.0 animations:^{ 
     [aboutView.view setAlpha:1]; 
    } completion:^(BOOL fin) { 
     // don't release it 
    }]; 
} 

-(IBAction)back { 
    [UIView animationWithDuration:1.0 animations:^{ 
     [aboutView.view setAlpha:0]; 
    } completion:^(BOOL fin) { 
     [aboutView.view removeFromSuperview]; 
     [aboutView release]; 
    }]; 
} 
+0

從Superview中移除aboutView後,viewDidAppear不會被調用。 – Houranis 2012-04-11 01:16:45

+0

@Houranis嗨,我已經編輯我的帖子,以反映管理視圖動畫沒有控制器的正確方式(因爲你說控制器委託沒有被調用)。 – 2012-04-11 12:27:15

0

這個問題可能是[self.view removeFromSuperview];-(IBAction)back;

你不需要這一點。在UIViewController中,只要您在dealloc中發佈它,它的視圖就會爲您處理。

AboutView將由控制器的視圖,當你addSubview:

此方法保留視圖,並將其下一個應答器的接收器,這是它的新上海華被保留。 - Google文件addSubview:

所以當視圖得到釋放,所以將aboutView

+0

那麼如何在不使用[self.view removeFromSuperview]的情況下在Second View中關閉self.view。 – Houranis 2012-04-11 03:05:35

+0

可能希望你想要做的就是把所有這個控制器放在UINavigationController棧中,然後彈出它。如果您在需要動畫的控制器上執行某些操作,則應將其添加到self.view中作爲子視圖,然後改爲使用子視圖的動畫效果。 – Allyn 2012-04-11 15:28:04

0

似乎沒有任何的方法之後被保持aboutView對象 ' - (IBAction爲)swichView'

線 '[self.view addSubview:aboutView.view];'

會給出額外的引用計數到aboutView.view,但不aboutView本身。

我可能會使用類似於UIPopoverViewController工作的委託模型。

定義與方法的protocal沿

-(void) subViewClosed:(AboutView*)aboutView; 

的線條使母公司實現它,然後去:

家長

-(IBAction)swichView { 
    .. existing stuff .. 

    (dont release) 

    aboutView.delegate = self; 
} 

AboutView類

-(IBAction)back { 
    ... existing stuff ... 

    [self.delegate subViewClosed:self]; 
} 

-(void) subViewClosed:(AboutView*)aboutView{ 
    [aboutView release]; 
} 
+0

我無法從AboutView ViewController調用subViewClosed,因爲它在父視圖控制器中定義,self.delegate無效行。 – Houranis 2012-04-11 16:54:50