Swift - How to set singleton to zero

I am writing an application in swift and using singleton to share an object of the User class in the application. I want this singleton to be set to "nil" when the user logs out, so that when they return to the old properties, it no longer exists (for example, name, username, etc.). I hope there is an easy way to just set singleton back to zero, instead of setting each property to nil.

Here is my User class, which is used in the application as User.activeUser:

class User: NSObject { class var activeUser : User? { struct Static { static let instance : User = User() } return Static.instance } } 

How can I change this so that the code below does not give me a warning and actually deduces a singleton object from it:

 User.activeUser = nil 
0
source share
2 answers

This should work:

 private var _SingletonSharedInstance:MyClass! = MyClass() class MyClass { let prop = "test" class var sharedInstance : MyClass { return _SingletonSharedInstance } init () {} func destroy() { _SingletonSharedInstance = nil } } 

But then the object references are still preserved, so you need to take some extra steps to invalidate the method calls in the class.

+3
source

Your activeUser is configured as a read-only computed property. Each time you call User.activeUser, it is about to rebuild ActiveUser for you. To set it to zero, you will have to add some logic to determine if the user is registered outside the computed property. Something like this will work:

 class User: NSObject { private struct userStatus { static var isLoggedIn: Bool = true } class var activeUser : User? { get { if userStatus.isLoggedIn { struct Static { static let instance : User = User() } return Static.instance } else { return nil } } set(newUser) { if newUser != nil { userStatus.isLoggedIn = true } else { userStatus.isLoggedIn = false } } } } 
0
source

Source: https://habr.com/ru/post/1237264/


All Articles