swift - 如何管理实例化的 viewController

标签 swift xcode uiviewcontroller viewcontroller

总而言之,管理 VC 的最佳方式是什么?

就我而言,我的游戏中有 3 个 VC。要在它们之间切换,当前 VC 中的一个按钮会激活以下代码:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier:"firstLevel")
self.present(viewController, animated: false, completion: nil)

此代码有效,但每次它实例化一个新的 VC 时,当存在相同 VC 的两个副本时,这会在我的游戏中导致全局变量(例如“Score”)出现问题,我认为这对内存也很不利。

这个问题的最佳解决方案是什么?

我是否应该在实例化下一个 VC 后通过放置以下代码行来关闭当前的 viewController?:

self.dismissViewControllerAnimated(false, completion: nil)

最佳答案

通过替换 rootViewController,您只需要 1 个 vc

 let viewController = storyboard!.instantiateViewController(withIdentifier:"firstLevel")
(UIApplication.shared.delegate as! AppDelegate).window!.rootViewController = viewController 

由于您当前的代码在堆栈中留下了旧的 vcs,这肯定会导致内存问题

关于swift - 如何管理实例化的 viewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53961257/

相关文章:

ios - 将自定义 UITableViewCell 从 nib 加载到 Swift 中的 UIViewController

swift - 在单元测试中等待 Alamofire

ios - Moya+Alamofire POST 请求在应用程序之间切换或进入后台时超时

ios - 如何在 Xcode View 层次结构中拥有深度 View ?

ios - XCTest 错误 : The bundle couldn’t be loaded. 尝试重新安装 bundle

Xcode 4.3 : how to create a nib linked to a view controller

ios - self.tableView 为零,与调用 numberOfSections TableView 的 uitableview 不同

ios - 使用 Swift 时出现错误 "nil requires a contextual type"

ios - 转换为ARC:将保留属性转换为unsafe_unretained?

ios - 通过 segue 传递错误的数据