gpt4 book ai didi

iOS10 : How to avoid memory leaks in a segue circle

转载 作者:搜寻专家 更新时间:2023-10-31 08:25:10 25 4
gpt4 key购买 nike

我的项目中有4个场景,page1可以segue(type is show)到page2,然后可以segue到page3,然后到 page4,然后返回到 page1

你在 1 秒内从我的 Storyboard中了解到:

enter image description here

这四个场景的controller类是ViewController:

import UIKit

class ViewController: UIViewController {

static var count: Int = 1

var id = count

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
ViewController.count += 1
print("ViewController#\(id) inited.")
}

deinit {
print("ViewController#\(id) deinited.")
}

override func viewDidLoad() {
super.viewDidLoad()
print("ViewController#\(id) loaded.")
}

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("ViewController#\(id) appeared.")
}

override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("ViewController#\(id) disappeared.")
}

}

然后在我完成 segue circle(page1 > page2 > page3 > page4 > page1) 后,它输出:

ViewController#1 inited.
ViewController#1 loaded.
ViewController#1 appeared.
ViewController#2 inited.
ViewController#2 loaded.
ViewController#2 appeared.
ViewController#1 disappeared.
ViewController#3 inited.
ViewController#3 loaded.
ViewController#3 appeared.
ViewController#2 disappeared.
ViewController#4 inited.
ViewController#4 loaded.
ViewController#4 appeared.
ViewController#3 disappeared.
ViewController#5 inited.
ViewController#5 loaded.
ViewController#5 appeared.
ViewController#4 disappeared.

这不是我想要的。我认为我的堆中有 5 个 ViewController(因为没有调用 deinit)。事实上,我们只需要 1 个 ViewController 来控制 page1。我应该怎么做才能销毁应用程序堆中的 4 个无用的 ViewController?

最佳答案

呈现/解散

注意:

如果您正在使用导航 Controller ,您可能需要查看我关于 Pushing/Popping 的回答


第四个View Controller-中“Back To Page1”的 Action 应该类似于:

@IBAction func backToPage01Tapped(_ sender: Any) {
presentingViewController?.presentingViewController?.presentingViewController?.dismiss(animated: true, completion: nil)
}

注意为什么数量为presentingViewController的原因是三个,因为它是第四个之前的 View Controller 的数量。

如果您之前只有两个 View Controller,那么您必须向后链接两次并从两个 View Controller 返回调用 dismiss:

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

等等……

关于iOS10 : How to avoid memory leaks in a segue circle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41014385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com