Since the shared singleton instance will always be around, can we safely use [unowned self]
in all closures within that singleton class?
Safe to always use [unowned self] for Swift singletons?
1.4k views Asked by SchoonSauce At
2
There are 2 answers
0
On
Sure, it's safe. But that's not a good reason.
Whether you use weak references or strong references should be based on the memory management characteristics in the function you are writing. For example, if a closure is referred to strongly by the object, then the closure should capture a weak reference to the object; and that is safe since nobody else has a reference to the closure, so it only can execute while the main object is alive, etc. If there is no retain cycle, and the closure is given to a separate API so that it is not tied to the lifetime of the main object, then the closure should have a strong reference to the main object. This reasoning applies equally for singletons and non-singletons alike.
Yes the singleton holds a strong reference to itself, and can't be disposed.
Base on that is safe to say that you can safely create weak or unowned references to it.
From Apple documents:
An easy way to test it is to test from the main class.
Between the first (disposed) class and the second (newly created) class there are no references to the singleton.