ios - 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
解决方案
正如@StevenFisher 在评论中所建议的那样,问题不是绿色突出显示的行本身,而是我忽略的闭包并且没有用[weak self]
. 我读过文章说按下不露面的面孔会将您带到有问题的代码行,但史蒂夫指出这可能不是问题,而是可以/将带您到问题开始的地方。在我的情况下,它让我知道我在文件中的某个地方遇到了问题,因为它被实例化了,而不是行本身。
推荐阅读
- c++ - 如何从映射值初始化 Int,C++
- mysql - 计算最小值和每行值之间的差异
- dataframe - Julia - 线性回归 - 错误:DimensionMismatch
- rust - 我需要推送包含的结构成员的(Vec),他也是一个结构
- python - 在python中生成一个不包括某些特殊字符的随机字符串
- javascript - 查询未在变量中产生结果
- python-2.7 - Pip2错误:找不到满足要求tensorboard<1.15.0,>=1.14.0的版本
- node.js - 依次执行节点应用程序中收到的 webhook
- kubernetes - 无法使用入口连接到 pod
- php - Woocommerce - 伙计们,我正在尝试显示 3 个随机产品,但跳过了前 3 个最近添加的产品