在多个UIViewController一起工作的应用程序中,
firstViewController已添加到根目录。到这里为止一切正常,现在我想转到secondViewController,我不想使用UINavigationControllerUITabBarController。我已经阅读了View Controller Programming Guide,但未使用UINavigationController, UITabBarController and story board时未指定。

当用户想从secondViewController移到firstViewController时,如何销毁secondViewController

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

最佳答案

如果您担心 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
查看取消分配保留计数1

如果要分配和初始化ViewController,则您是其生命周期的所有者,必须在 push或modalPresent 之后释放它。
alloc init时的上述输出中,SecondViewController的保留计数为1,令人惊讶,但逻辑上,即使已将其保留,保留计数仍为1(请参见dealloc方法),因此需要在FirstViewController中释放以完全释放破坏它。

10-08 08:19
查看更多