gpt4 book ai didi

ios - Swift 保留周期解释

转载 作者:IT王子 更新时间:2023-10-29 05:42:36 27 4
gpt4 key购买 nike

这是我的自定义 View :

class CustomVIew: UIView {

deinit {
print("custom view deinit")
}

var onTapViewHandler: (()->Void)?
}

和 View Controller :

class ViewControllerB: UIViewController {

var customView: CustomVIew!

deinit {
print("B deinit")
}

override func viewDidLoad() {
super.viewDidLoad()

let customView = CustomVIew()
customView.onTapViewHandler = { [unowned self] in
self.didTapBlue()
}
customView.frame = CGRect(x: 50, y: 250, width: 200, height: 100)
customView.backgroundColor = UIColor.blueColor()
view.addSubview(customView)

self.customView = customView

}

func didTapBlue() {

}
}

当 Controller 从导航堆栈中弹出时,一切正常:

B deinit
custom view deinit

但是当我替换这段代码时:

customView.onTapViewHandler = { [unowned self] in
self.didTapBlue()
}

用这个:

 customView.onTapViewHandler = didTapBlue

然后,控制台上不会打印任何内容。 CustomView 和 ViewController 没有发布,为什么?

为什么 customView.onTapViewHandler = didTapBlue 捕获对 self 的引用?

最佳答案

Swift 函数是一种闭包。所以像 closure(Block in objective c) does functions can capture references.

customView.onTapViewHandler = didTapBlue 执行对 self 的引用时,即 ViewControllerB 引用在这种情况下将被函数调用捕获。

同时 ViewControllerB 的 View 持有对 CustomVIew 的强引用,因此它形成了保留循环。

关于使用unownedApple document说:

Weak and unowned references enable one instance in a reference cycle to refer to the other instance without keeping a strong hold on it. The instances can then refer to each other without creating a strong reference cycle.

这意味着没有循环引用和保留周期。

关于ios - Swift 保留周期解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38939489/

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