Search code examples
iosswiftmemoryclosuresblock

Swift weak reference confusion


var label1: UILabel? = UILabel()

weak var label2 = label1

label1 = nil

Here's some confusion: After these 3 lines, label1 is nil, but label2 still have the reference. From my understanding, it should be nil since it's weak, so it won't have strong hold of the reference.

So, why doesn't this work?

Another question:

func request() { [weak self] complete in
    guard let strongSelf = self else { return }
    strongSelf.printSomething()
    strongSelf.doSomething()
}

In the internet request callback, I specify weak self, and guard to have a strongSelf to make sure it will success if self hasn't been deallocated. The question is, if when the line after guard runs, the self get deallocated somewhere else, would strongSelf still live? does it have strong hold to the self? (add +1 reference count to self, so memory of self won't get released?)


Solution

  • Using playground, try this:

    class Node {}
    
    var node1: Node? = Node()
    weak var node2 = node1
    node1 = nil
    print(node2 ?? "node2 is nil!")
    

    UILabel is behaving differently because, as Paulw11 was suggesting, is being retained by the PlaygroundPage itself