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

时间:2018-07-13 21:21:54

标签: ios swift memory closures retain-cycle

当我在闭包中引用self时,我理解了带闭包的典型保留周期,但是,为什么标签不产生保留周期呢?我已经测试过注释掉testClosure与注释掉标签,只有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)
    }
}

1 个答案:

答案 0 :(得分:0)

如注释中所述:您为UILabel自定义的初始化程序只运行label块,但不存储(读取:不保留),因此没有保留周期可能会发生。

请不要从外部确定您是否保留了块参数,因此,除非对此行为进行了记录或您自己编写了代码,否则通常最好使用弱引用来确定。