Is there no save loop in my myClass2?

Can someone help explain why obj2 will get deinit? (I think there is a save cycle)

obj2 and obj1 are so similar: they both have a property called printNameLength, which both are closures, which both capture themselves (or is this?).

But obj2 get deinit (although obj1 is not because there is a save loop), it surprised me, and I can’t understand why.

Many thanks.

class myClass1 {

    var name: String

    lazy var printNameLength: ( () -> Int ) = { // [unowned self]
        return self.name.characters.count  // retain cycle here
    }

    init(name: String){
        self.name = name
    }

    deinit {
        print("deinit myClass1: \(name)")
    }

}

var obj1: myClass1? = myClass1.init(name: "obj1")
print(obj1!.printNameLength())
obj1 = nil    //  never get deinit



class myClass2{
    var name: String

    init(name: String){
        self.name = name
    }

    var printNameLength: ( () -> Int )?

    deinit {
        print("deinit myClass2: \(name)")
    }
}

var obj2: myClass2? = myClass2.init(name: "obj2")
obj2!.printNameLength = {
    return obj2!.name.characters.count   // no retain cycle here?
}
print(obj2!.printNameLength!())
obj2 = nil   //  get deinit
+4
source share
1 answer

In the second case, the save loop is saved first, but it breaks when you set the variable obj2to nil.

Swift (, Objective-C, ​​__block), , ( ). myClass2 obj2, ; obj2 nil, .

0

Source: https://habr.com/ru/post/1687073/


All Articles