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?
Your code will most likely only work in the playground, where the memory management is a little... fuzzy.
When I ran this in Xcode, it crashes as you'd expect. The playground is meant to make it easy to test the syntax, play with some classes, etc. It's not the best place to play around with weak/unretained variables.
I haven't found any documented sources describing how exactly the memory is managed in a playground, but it's definitely different from how it will be in an actual runtime.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.