【发布时间】:2020-01-28 04:29:46
【问题描述】:
我想了解闭包中的内存管理。
例如,我们有一个视图控制器,它需要完成一个闭包。当我检查对视图控制器的引用计数时,它显示引用计数 1。
什么时候会清除/移除已关闭视图控制器的内存?
这是我的代码。
class ViewController: UIViewController {
@IBOutlet weak var buttonToHide: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func showSecondViewController() {
guard let second = self.storyboard?.instantiateViewController(withIdentifier: "second") else { return }
present(second, animated: true, completion: nil)
}
}
class SecondViewControler: UIViewController {
@IBOutlet weak var lbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
deinit {
print("\(self) is being deinitialized") // still self object is there
print(_getRetainCount(self)) // returning 1
}
@IBAction func dismissController() {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(6)) {
self.lbl.text = "HHi"
print("self reference : ",self.lbl.description)
}
self.dismiss(animated: true, completion: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidAppear(animated)
print("viewDidDisappear", self.lbl.description)
}
}
【问题讨论】:
-
请参考下面的闭包的强参考循环,你会很清楚它是如何工作的。 docs.swift.org/swift-book/LanguageGuide/…
-
我认为除非
deinit方法完成,否则引用计数将为 1。所以在完全关闭后检查引用计数。