Home > Software design >  Do I need to keep the reference to a singleton object to avoid repeated initialisation?
Do I need to keep the reference to a singleton object to avoid repeated initialisation?

Time:10-18

Imagine that we have some singleton object:

class Singleton {
    static var shared = Singleton()

    private init() { ... }
}

Am I right that if I don't keep the reference in some place, it is initialised again and again due to the ARC every time I access it, like this:

Singleton.shared.doSomething()
var a = Singleton.shared.returnSomething()

If I am, where to keep the reference in the iOS app? In classes that use the singleton? Or in AppDelegate, to ensure using the same instance without repeated initialisation?

CodePudding user response:

By assigning it to a static value you retain the shared instance and don't need to reinitialise it. Static values exist at class level, not instance level, so are retained, effectively, indefinitely.

  • Related