这些闭包中的保留周期之间有什么区别?标准闭包与对象初始化闭包



当在闭包中引用self时,我理解带有闭包的典型保留循环,但标签不产生保留循环是有原因的吗?我测试了注释testClosure-out和注释label-out,只有testClosure产生了一个保留周期

class TargetView: UIView {
let newText = "hi"
var label = UILabel()
private var counter = 0
private var testClosure : (() -> ()) = { }
init() {
super.init(frame: .zero)
// This causes a retain cycle
testClosure = {
self.counter += 1
print(self.counter)
}
// This does NOT cause a retain cycle
label = UILabel() {
$0.text = self.newText
self.counter += 1
} 
}
required init?(coder aDecoder: NSCoder) { fatalError() }
deinit {
print("view deinit!")
}
}
extension UILabel {
convenience init(label: (UILabel) -> Void) {
self.init()
label(self)
}
}

如注释中所述:UILabel的自定义初始值设定项只运行label块,但不存储(读取:不保留(,因此不会发生保留循环。

请注意,从外部来看,您无法确定是否保留了块参数,因此,除非记录了这种行为或您自己编写了代码,否则通常最好使用弱引用来确定。

最新更新