I think I know what't a retain cycle is on Swift and why it produces a memory leak. But I wrote a small example to demonstrate it and seems the code is correctly deallocated anyway.
In this example I have two objects that retain each other (creating the retain cycle) and a third object is strongly holding both.
I would expect that also this third object is impossible to deallocate, but it's not.
The two objects that retain each other:
class Obj1: NSObject {
var objc2: Obj2?
deinit {
print("Obj1 Deinit")
}
}
class Obj2: NSObject {
var obj1: Obj1?
deinit {
print("Obj2 Deinit")
}
}
The container:
class Container {
var obj1: Obj1?
var obj2: Obj2?
deinit {
print("Container Deinit")
}
}
The code that generates the retain cycle
let obj1 = Obj1()
let obj2 = Obj2()
obj1.objc2 = obj2
obj2.obj1 = obj1
let c = Container()
c.obj1 = obj1
c.obj2 = obj2
The result on the console is:
Container Deinit
Can someone point out why the Container is deallocated even if its properties are not?
There's no object holding the container other than your
let c = Container()constant.The properties of an object do not hold a reference to its "parent" object (unless you keep an explicit non-weak and non-unowned reference to it).
Since swift uses ARC (automatic reference counting) it may be helpful to keep the count of references manually to see what's going on:
Notice that if you change the order of deallocations (first obj1 and obj2 and afterwards c), the end result doesn't change.
Hope that explains this thing. :)