需要有关UIViewController的帮助

时间:2013-05-02 08:42:20

标签: ios objective-c memory-management

在多个UIViewControllers协同工作的应用程序中,

firstViewController添加到root。现在好了,我想转到secondViewController我不想使用UINavigationControllerUITabBarController。我已经阅读了View Controller Programming Guide,但未使用UINavigationController, UITabBarController and story board进行指定。

当用户想要从secondViewController移动到firstViewControllersecondViewController将会被销毁?

Apple Doc也没有指定如何释放或销毁UIViewController?它只告诉UIViewController内的生命周期。

4 个答案:

答案 0 :(得分:2)

如果您担心如何释放或销毁 UIViewController ,那么这里有一个场景: -

这是FirstViewController中的按钮点击方法,它提供了 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 init 时的上述输出中,保留SecondViewController的计数是One ,,,令人惊讶但逻辑上它的保留计数仍然是一个甚至在它被释放后(参见dealloc方法),所以需要一个在FirstViewController中释放以完全销毁它。

答案 1 :(得分:1)

呈现新视图控制器的其他方式就像模态视图控制器一样(注意self是firstViewController):

[self presentModalViewController:secondViewController animated:YES];

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

[self dismissModalViewControllerAnimated:YES];

希望有所帮助。

答案 2 :(得分:1)

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

答案 3 :(得分:0)

然后,您可以采取其他策略,不是最好的构建您的视图控制器层次结构,但它也可以工作。您可以在firstViewController上覆盖secondViewContrller的视图,并使secondViewController成为firstViewController中的子视图:

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

当您想要删除视图控制器时,您必须删除视图并要求视图控制器从其父级中删除:

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

但是你必须自己控制视图层次结构(自己放置和删除视图和视图控制器)。

相关问题