Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 256
SchoonSauce Avatar asked Mar 16 '23 21:03

SchoonSauce


2 Answers

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.

like image 183
newacct Avatar answered Mar 18 '23 10:03

newacct


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.
like image 23
Icaro Avatar answered Mar 18 '23 09:03

Icaro