簡體   English   中英

將UIViewController添加到子視圖並將其刪除的最正確方法是什么?

[英]What is the most correct way to add a UIViewController to a subview and remove it?

我試圖添加一個UIViewController子視圖,然后單擊按鈕將其關閉。 我當前的代碼可以完成任務,但是我不確定它是否會泄漏或引起任何問題。

所以首先我添加子視圖

-(IBAction)openNewView:(id)sender{
   // start animation
   [UIView beginAnimations:@"CurlUp" context:nil];
   [UIView setAnimationDuration:.3];
   [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
   [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];

   // add the view
   newViewController* newVC = [[newViewController alloc] initWithNibName:@"newViewController" bundle:[NSBundle mainBundle]];
   [self.view addSubview:newVC.view];

   [UIView commitAnimations]; 
}

然后在newViewController.m中,我有刪除它的功能

-(IBAction)closeNewView:(id)sender{
   // start animation
   [UIView beginAnimations:@"curldown" context:nil];
   [UIView setAnimationDelegate:self];
   [UIView setAnimationDuration:.3];
   [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
   [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view.superview cache:YES];

   // close dialog
   [self.view removeFromSuperview];
   [UIView commitAnimations];

   [self.view release];
}

就像我說的那樣有效,但是當我分析代碼時,它告訴我:

X線上分配並存儲到“ newViewController”中的對象的潛在泄漏:

newViewController* newVC = [[newViewController alloc] initWithNibName:@"newViewController" bundle:[NSBundle mainBundle]];

[self.view release];的調用者此時未擁有的對象的引用計數的錯誤減少[self.view release];

如果我autorelease viewController而不是[self.view release] self.view [self.view release]它會在刪除時崩潰(如果我在添加視圖后也釋放了視圖),則使用以下命令會崩潰:-[FirstViewController performSelector:withObject:withObject:]:消息發送到已釋放實例0xd21c7e0

如果我叫[newVC release]在任一viewControllers dealloc它未能建立。

希望我不會問一個明顯的問題,但是添加和刪除viewControllers的正確方法是什么?

您正在使用哪個IOS版本? 如果您使用的是5.0,則應該繼續使用ARC,這樣就不必自己處理[release]調用。

如果您仍然希望或需要堅持手動進行內存管理:嘗試釋放newVC時無法創建dealloc的原因是因為該指針的作用域為openNewView函數。 使其成為班級成員,就可以釋放它。

@implementation WhateverItsCalled {
  newViewController *newVC;
}

- ( IBAction ) openNewView: (id)sender {
...
  newVC = [ [ newViewController alloc ] initWithNibNamed:...
}

- ( void ) dealloc {
  [ newVC release ];
}

是的,如果您不使用ARC,則每個“分配”都必須與相應的“發行版”配對。

我還必須問-為什么在這里全部使用視圖控制器? 如果只需要視圖,則可以使用[[NSBundle mainBundle] loadNibNamed]從NIB加載視圖,並將[self]列為文件的所有者。 這將設置您的所有引用(包括所需的視圖),並且您不必實例化(看起來像)一個多余的視圖控制器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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