[Swift ARC] What will happen to weak references of the object when object is calling deinit?

Kuang Lin
2 min readAug 2, 2019

--

I believe we are all aware of that the weak var will be nil when the object is killed. But….

What will happen to weak references when the object is calling deinit?

First, let’s make a class A and B withinit and deinit function.

class A {
var b: B!
init() {
b = B(a: self)
}
deinit {
print("is property a in b still alive?: \(b.a != nil)")
}
}
class B {
weak var a: A?
init(a: A) {
self.a = a
}
}

As we can see, we put A itself into class B , and we will check if the property in that class is still alive during the deinit function is executing.

So we get the conclusion that…

When object is calling deinit, the weak reference will be nil.

But this brings another question…

Is the object dead when deinit is called?

The answer is … Of course not!

Let’s do this:

class A {
var b: B!

init() {
print("a init")
b = B(a: self)
}

deinit {
print("is property b.a still alive? \(b.a != nil)")
// is property b.a still alive? false
b.checkA(a: self)
}
}
class B {
weak var a: A?
init(a: A) {
self.a = a
}
func checkA(a: A) {
print("is a nil? \(a == nil)") // is a nil? false
}
}

We pass the reference to b again in deinit , and check if a.self is nil.

The result is not.

Conclusion

  1. The weak references will be nil when deinit of the object is called.
  2. The object is still alive, aka not nil in deinit function.

--

--

Kuang Lin
Kuang Lin

No responses yet