How to destroy a singleton in Swift

后端 未结 3 1519
情书的邮戳
情书的邮戳 2020-12-28 17:38

How to destroy a singleton in Swift?

I create a singleton like this:

class MyManager  {
    private static let sharedInstance = MyManager()
    cla         


        
3条回答
  •  心在旅途
    2020-12-28 18:15

    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.

提交回复
热议问题