需要关于UIViewController的帮助

在多个UIViewController一起工作的应用程序中,

firstViewController添加到根。 直到现在它罚款现在我想去secondViewController我不想使用UINavigationControllerUITabBarController 。 我已经阅读了“ 视图控制器编程指南”,但没有使用UINavigationController, UITabBarController and story board

当用户想从secondViewController移动到firstViewController如何secondViewController将被销毁?

苹果文件也不指定UIViewController如何释放或销毁? 它只是告诉UIViewController里面的生命周期。

如果你关心UIViewController是如何被释放或者被破坏的,那么这里是你的一个场景:

这里是FirstViewController中的button抽头方法,它提供了SecondViewController (使用pushViewController,presentModalViewController等)

在FirstViewController.m文件中

 - (IBAction)btnTapped { SecondViewController * secondView = [[SecondViewController alloc]initWithNibName:@"SecondViewController" bundle:nil]; NSLog(@"Before Present Retain Count:%d",[secondView retainCount]); [self presentModalViewController:secondView animated:YES]; NSLog(@"After Present Retain Count:%d",[secondView retainCount]); [secondView release]; //not releasing here is memory leak(Use build and analyze) } 

现在在SecondViewController.m文件中

 - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"View Load Retain Count %d",[self retainCount]); } - (void)dealloc { [super dealloc]; NSLog(@"View Dealloc Retain Count %d",[self retainCount]); } 

运行代码之后:

在推保留计数之前:1
查看负载保留计数3
推后保留计数:4
查看Dealloc保留计数1

如果您正在分配和初始化ViewController,则您是其生命周期的所有者,您必须在push或modalPresent之后其释放。 在上面的输出的时候, alloc保留了SecondViewController的计数是1 ,,,,但是在令人惊讶的但是在逻辑上它的保留计数仍然是One,即使它已经被释放(见dealloc方法),所以需要在FirstViewController中释放一个来彻底销毁它。

其他的方式来呈现一个新的视图控制器就像一个模式视图控制器(注意自己是firstViewController):

 [self presentModalViewController:secondViewController animated:YES]; 

然后,当你想回到firstViewController并销毁secondViewController时,你必须closures视图控制器(从secondViewController):

 [self dismissModalViewControllerAnimated:YES]; 

希望有所帮助。

您可以使用UINavigationController移动到secondViewController,并通过将UINavigationController属性“navigationBarHidden”设置为YES返回。 这将隐藏导航栏。 视图控制器的释放和销毁将由此照顾。

那么,你可以采取其他的策略,不是最好的build立你的视图控制器层次结构,但它也可以工作。 你可以覆盖firstViewController的第二个ViewContrller视图,并使第二个ViewController成为firstViewController的子视图:

 //... [self addChildViewController:secondViewController]; [self.view addSubview:secondViewContrller.view]; //... 

而当你想删除视图控制器,你必须删除视图,并要求视图控制器从他的父母删除:

 //... [self.view removeFromSuperview]; [self removeFromParentViewController]; //... 

但是,您将不得不通过自己的方式控制视图层次结构(放置和删除视图和视图控制器)。