通过应用程序委托管理多个UINavigationControllers,确保UINavigationController正确释放。

7

我有一个应用程序,其中使用了两个UINavigationController——一个用于菜单系统,另一个用于实际游戏。在我的appDelegate中声明了一个常见的UINavigationController。当应用程序加载时,它会加载菜单或游戏的UINavigationController。当然,玩家可以在两者之间导航。

从菜单到游戏时,我创建一个新的UINavigationController,并按以下方式呈现:

    GameViewController *rootController = [[GameViewController alloc] init];
     UINavigationController *newNavController = [[UINavigationController alloc] initWithRootViewController:rootController];
     [rootController release]; 
     newNavController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
     [self presentModalViewController:newNavController animated:YES];
[newNavController release];

然而,我注意到当我这样做时,菜单的视图控制器从未调用dealloc。可能是因为仍然有一个引用使其保持活动状态。我发现当我显式地将应用程序委托的UINavigationController设置为新的导航控制器(在释放新的navController之前),它会释放菜单。我按照以下方式执行此操作:

MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate]; 
 appDelegate.navController = newNavController;
 [newNavController release];

这是一个好的实践吗?我发现当从游戏返回到菜单时,相同的技巧似乎不起作用。即

MainMenuViewController *menuViewController = [[MainMenuViewController alloc] init]; 
 UINavigationController *newNavController = [[UINavigationController alloc] initWithRootViewController:menuViewController];
 [menuViewController release];
 newNavController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
 [self presentModalViewController:newNavController animated:YES];

 //Setting the appDelegate's navController to the new navController allows the menu to dealloc. 
 //This must happen AFTER the newNavController has been loaded. 
 MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate]; 
 appDelegate.navController = newNavController;
 [newNavController release];

在游戏的主ViewController上永远不要调用dealloc方法。当我再次返回游戏时,菜单的主ViewController也不再被释放。

当我操纵UINavigationControllers时,我是否遗漏了什么?

谢谢,

Michael

编辑:我后来意识到我的游戏主ViewController没有dealloc的原因是我有一些NSTimers没有失效!然而,我仍然想知道我的上述方法是否正确,明确地在App Delegate中重新定义navController是否是允许不同的UINavigationControllers dealloc的正确方式 :)


我对几件事感到困惑:1)如果你的应用程序是一个游戏,为什么要释放游戏的视图控制器?2)作为推论,为什么你要使用模态方式呈现游戏控制器?3)你用来呈现游戏和菜单控制器的视图控制器是什么(即在你的示例代码中 self 的类是什么,这个对象在你的应用程序中扮演什么角色)? - jlehr
  1. 这是一个相当简单的游戏,用户可以在菜单和游戏之间来回切换,所以我认为当他们进入菜单时卸载游戏只是一个好的实践。
  2. 我不确定如何展示游戏控制器以使其能够很好地翻转。我可以将其添加为窗口的子视图,但那样它就会突然改变,而我喜欢过渡效果。这是不好的做法吗?
  3. 我代码中的self是当前UINavigationController的rootViewController。这是不好的吗?
- Smikey
1个回答

8

让你的生活更轻松。使用单个UINavigationController,并维护两个独立的View Controller堆栈,它们只是UIViewController数组。您可以使用[UINavigationController setViewControllers:animated:]来仅交换堆栈并保留导航控制器。使用UINavigationController.viewControllers获取当前堆栈以在替换之前保存它。这比处理多个导航控制器的所有不确定性要容易和干净得多,大约轻松了14.3亿倍。


1
我应该在哪里进行开关 - 在应用程序委托中吗? - Smikey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接