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?
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 thisprivate
and use a function to fetch it. If the Singleton isnil
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.