1
votes
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?)

1
Have you added the label to a view? If so, the view will be holding a strong reference to it, so label2 won't be nil. In answer to your other question, yes strongSelf will prevent the object being releasedPaulw11
@Paulw11 no, I did the first test in Playground, only 3 lines of the code. labels are not inserted into any of the views. Re second answer, does it mean that strongSelf adds reference count + 1 to the weak self so it will be fine?Tony Lin
You can’t trust the playground for this sort of stuff. Test it in a real appPaulw11
@Paulw11 actually I did try that in the real project, still gives same result..Tony Lin
@paulw11 actually, you are right, just did some test to make it workTony Lin

1 Answers

2
votes

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