Circular reference
In Swift, Closure is something very popular which We may have to use on a daily basis, however sometimes careless in using.
There is a potential risk in using closure, that is memory leak. Memory leak is the case in which you have given up access to the object which is not able to be deinited due to circular strong references it gets involved.
In case of objects relationship, A refers to B, and B refers back to A. We’re easily to find out a strong circular reference and easy to break it down by turning one of references to weak/unowned reference. This is the case We usually know
In the post, I bring up the second case which We usually pay less attention. The circular reference caused by relationship between an object and a closure.
Give an example
Open the XCode, create a playground and try this sample
In the above piece of code, at the line #19 to #21 the class Student has var summaryInfo which holds a closure to print out the summary info of student itself. The point is the closure refers back to the object to take what it needs.
Student -> closure -> Student.
This obviously makes up a circular reference, and the references are strong. So the objects of student class will not stand a chance to be deallocated.
In the console, it doesn’t show an info about object deinit when student goes out of scope, because the object is retained. This is bad.
Resolve
In the given sample, We see the pattern. In order to break down the strong relationship, We may define an either weak or unowned reference in closure
We still have a circular reference, but one reference is strong and the other one is weak. They don’t retain each other.
So now re-run the code, we’ll see the student object gets deallocated when it goes out of scope.
This is what We want. Good luck.