Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destroy a singleton in Swift

Tags:

How to destroy a singleton in Swift?

I create a singleton like this:

class MyManager  {     private static let sharedInstance = MyManager()     class var sharedManager : MyManager {         return sharedInstance     } } 
like image 288
Dennis Avatar asked Nov 04 '15 14:11

Dennis


People also ask

How do you destroy a singleton object in Swift?

You don't destroy a singleton. A singleton is created the first time anyone needs it, and is never destroyed as long as the application lives.

How do you destroy singleton?

If you really need to reset a singleton instance (which doesn't makes much sense actually) you could wrap all its inner members in a private object, and reinitialize via an explicit initialize() and reset() methods. That way, you can preserve your singleton istance and provide some kind of "reset" functionality.

How do you destruct a singleton object?

To design C++ delete singleton instance, first, we need to make the singleton class destructor private, so, it can not be accessed from outside of the class. Hence, user cannot delete the singleton instance using the keyword “delete”.

Can we Deinit a singleton object?

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.


1 Answers

Just a simple example on how to dispose the current instance of a Singleton:

import UIKit  class AnyTestClass {     struct Static     {         private static var instance: AnyTestClass?     }      class var sharedInstance: AnyTestClass     {         if Static.instance == nil         {             Static.instance = AnyTestClass()         }          return Static.instance!     }      func dispose()     {         AnyTestClass.Static.instance = nil         print("Disposed Singleton instance")     }      func saySomething()     {         print("Hi")     }  }  // basic usage AnyTestClass.sharedInstance.saySomething() AnyTestClass.sharedInstance.dispose() 

Hope it might help.

like image 83
brduca Avatar answered Sep 23 '22 08:09

brduca