首页 > 解决方案 > Swift iOS -storyboard.instantiateViewController(withIdentifier:) 导致保留周期

问题描述

我正在使用我的物理设备而不是模拟器。

我正在实例化一个 vcstoryboard.instantiateViewController(withIdentifier:)并以模态方式呈现它。我使用presentingViewController?.dismiss(animated: true, completion: nil). 在提供的 vc 中,我有一个Deinit永远不会运行的 print 方法。

我去了Instruments > Allocations > Statistics > Allocation Summary > MyApp.ThePresenedController,它显示 2 张面孔说有问题。当我点击它们时,它把我带到了展示 vc 的代码,我在其中实例化了要展示的 vc 并将其突出显示为绿色。在呈现的 vc 被解除后,它不会从分配摘要列表中删除。在呈现的 vc 内部没有对呈现 vc 的引用,所以这不是weak var问题。

在此处输入图像描述

在此处输入图像描述

怎么storyboard.instantiateViewController(withIdentifier:)给我惹了麻烦?

介绍VC:

@IBAction func forgotPasswordButtonTapped(_ sender: UIButton) {

    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let forgotPasswordVC = mainStoryboard.instantiateViewController(withIdentifier: "ForgotPasswordController") as! ForgotPasswordController
    let navVC = UINavigationController(rootViewController: forgotPasswordVC)
    present(navVC, animated: true, completion: nil)
}

介绍VC:

@IBAction func cancelButtonTapped(_ sender: UIButton) {

    presentingViewController?.dismiss(animated: true, completion: nil)
}

deinit{
    print("I've been dismissed")
}

我也在storyboard.instantiateViewController(withIdentifier:)AppDelegate 中使用相同的代码,并且发生了相同的 2 个面孔和突出显示的绿色错误。

AppDelegate didFinishLaunching:

let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

if userDoesThis {

    // if true this first line will highlight green
    let thisVC: ThisController = mainStoryboard.instantiateViewController(withIdentifier: "ThisController") as! ThisController
    let nav = UINavigationController(rootViewController: thisVC)

} else {

    // if false this first line will highlight green
    let thatVC: ThatController = mainStoryboard.instantiateViewController(withIdentifier: "ThisController") as! ThatController
    let nav = UINavigationController(rootViewController: thatVC)
}

window?.rootViewController = nav
window?.makeKeyAndVisible()
return true

标签: iosswiftuiviewcontrolleruistoryboardretain-cycle

解决方案


正如@StevenFisher 在评论中所建议的那样,问题不是绿色突出显示的行本身,而是我忽略的闭包并且没有用[weak self]. 我读过文章说按下不露面的面孔会将您带到有问题的代码行,但史蒂夫指出这可能不是问题,而是可以/将带您到问题开始的地方。在我的情况下,它让我知道我在文件中的某个地方遇到了问题,因为它被实例化了,而不是行本身。


推荐阅读