Singleton in Swift

后端 未结 4 1640
盖世英雄少女心
盖世英雄少女心 2020-11-28 08:45

I\'ve been trying to implement a singleton to be used as a cache for photos which I uploaded to my iOS app from the web. I\'ve attached three variants in the code below. I

4条回答
  •  醉梦人生
    2020-11-28 09:33

    Following are the two different approaches to create your singleton class in swift 2.0

    Approach 1) This approach is Objective C implementation over swift.

    import UIKit
    
    class SomeManager: NSObject {
    
           class var sharedInstance : SomeManager {
    
                  struct managerStruct {
    
                       static var onceToken : dispatch_once_t = 0
                       static var sharedObject : SomeManager? = nil
                  }
    
                  dispatch_once(&managerStruct.onceToken) { () -> Void in
                       managerStruct.sharedObject = SomeManager()
                  }
                  return managerStruct.sharedObject!
           }
    
           func someMethod(){
                  print("Some method call")
           }
     }
    

    Approach 2) One line Singleton, Don't forget to implement the Private init (restrict usage of only singleton)

    import UIKit
    
    class SomeManager: NSObject {
    
           static let sharedInstance = SomeManager()
    
           private override init() {
    
           }
    
           func someMethod(){
                print("Some method call")
           }
      }
    

    Call the Singleton method like :

      SomeManager.sharedInstance.someMethod()
    

提交回复
热议问题