Since the shared singleton instance will always be around, can we safely use [unowned self]
in all closures within that singleton class?
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:
The class lazily creates its sole instance the first time it is requested and thereafter ensures that no other instance can be created. A singleton class also prevents callers from copying, retaining, or releasing the instance.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With