Ios – How to reset singleton instance

iosswift

I'm creating a singleton instance like this

static let currentUser = User()

private override init() {
    super.init()
    // custom initialisation
}

How can I reset this instance or set back to nil?

Best Answer

I create all my Singletons with an optional Singleton instance. However I also make this private and use a function to fetch it. If the Singleton is nil it creates a new instance.

This is actually the only good way to set up a Singleton. If you have a regular object that you can't deinitialize it's a memory problem. Singletons are no different, except that you have to write a function to do it.

Singletons have to be completely self managed. This means from init to deinit.

I have a couple of templates on github for Singeltons, one of them with a fully implemented read/write lock.

class Singleton {

    private static var privateShared : Singleton?

    class func shared() -> Singleton { // change class to final to prevent override
        guard let uwShared = privateShared else {
            privateShared = Singleton()
            return privateShared!
        }
        return uwShared
    }

    class func destroy() {
        privateShared = nil
    }

    private init() {
        print("init singleton")
    }

    deinit {
        print("deinit singleton")
    }
}