【发布时间】:2018-08-19 01:01:53
【问题描述】:
我的 iOS 应用有两个 ViewController (VC)。当我按下 VC A 上的按钮时,它会显示 VC B。当我按下 VC B 上的按钮时,它会显示 VC A。这很好。然而,事实证明,每次切换时它都会为每个视图控制器创建一个新实例,这弄乱了我的应用程序的一些功能。我试图改变这一点。
正如您在下面看到的,我只是创建一个新的 VC 实例,前提是该实例尚不存在。我将 VC A 保存在 VC B 中,反之亦然。
VC A 文件:
var vcB: BViewController?
func leftPresentVC() {
if(vcB == nil) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
vcB = storyboard.instantiateViewController(withIdentifier: "vcB") as! BViewController
vcB?.transitioningDelegate = transition
vcB?.modalPresentationStyle = .custom
vcB?.vcA = self
}
present(vcB!, animated: true, completion: {})
}
VC B 文件:
var vcA: AViewController?
func rightPresentVC() {
if(vcA == nil) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
vcA = storyboard.instantiateViewController(withIdentifier: "vcA") as! AViewController
vcA?.transitioningDelegate = transition
vcA?.modalPresentationStyle = .custom
}
if let vcA = vcA {
present(vcA, animated: true, completion: {})
}
}
函数 leftPresentVC 和 rightPresentVC 在按钮按下时被调用。
所以问题是这样的。当我启动应用程序时,VC A 按计划加载。我单击一个按钮,VC B 按计划呈现。然后我单击一个按钮转到 VC A,然后应用程序崩溃了。我在 VC B 的 present(vcA, animated: true, completion: {}) 中收到一个错误,说 EXC_BAD_ACCESS,它给出了一个内存地址。知道可能是什么问题吗?
【问题讨论】:
标签: ios swift memory uiviewcontroller segue