Safe to always use [unowned self] for Swift singletons?

1.4k views Asked by At

Since the shared singleton instance will always be around, can we safely use [unowned self] in all closures within that singleton class?

2

There are 2 answers

6
Icaro On

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.

  • Create a new class (let's call "first class"), which initializes the singleton with some values and is disposed after finishing a unique job.
  • After that in the main class create another class (let's call "second class") which retrieves the singleton instance and reads its values.

Between the first (disposed) class and the second (newly created) class there are no references to the singleton.

  • Now read the values and if values still there it proves that the singleton has kept alive by its own reference.
0
newacct 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.