I was playing with unowned references. As I understood from the WWDC videos, unowned references can't be nil
, and they do not increase the retain count of whatever object they reference. I thought that if an unowned reference is deallocated, then the object that held the unowned reference is also deallocated.
Consider the following code:
class Parent {
var child : Child?
func foo() {
println("Hello")
}
}
class Child {
unowned let parent : Parent
init(parent: Parent) {
self.parent = parent
}
}
var parent : Parent? = Parent()
parent!.child = Child(parent: parent!)
weak var child = parent!.child
parent = nil
child!.parent.foo()
This code works! How come child
exists, and moreover, how come parent
apparently still exists? I had thought that after setting parent = nil
, child
would also be nil
. It seems as if the unowned reference is acting as if it were a strong reference.
Any ideas as to why this code works?