How to make a Swift Class Singleton instance thread safe?

与世无争的帅哥 提交于 2019-12-10 03:56:29

问题


I have a singleton class as so:

class Database {
   static let instance:Database = Database()
   private var db: Connection?

   private init(){
      do {
        db = try Connection("\(path)/SalesPresenterDatabase.sqlite3")
        }catch{print(error)}
   }
}

Now I access this class using Database.instance.xxxxxx to perform a function within the class. However when I access the instance from another thread it throws bizarre results as if its trying to create another instance. Should I be referencing the instance in the same thread?

To clarify the bizarre results show database I/o errors because of two instances trying to access the db at once

Update
please see this question for more info on the database code: Using transactions to insert is throwing errors Sqlite.swift


回答1:


class var shareInstance: ClassName {

    get {
        struct Static {
            static var instance: ClassName? = nil
            static var token: dispatch_once_t = 0
        }
        dispatch_once(&Static.token, {
            Static.instance = ClassName()
        })
        return Static.instance!
    }
}

USE: let object:ClassName = ClassName.shareInstance

Swift 3.0

class ClassName {
  static let sharedInstance: ClassName = { ClassName()} ()
}

USE: let object:ClassName = ClassName.shareInstance




回答2:


In Swift 3.0 add a private init to prevent others from using the default () initializer.

class ClassName {
  static let sharedInstance = ClassName()
  private init() {} //This prevents others from using the default '()' initializer for this class.
}


来源:https://stackoverflow.com/questions/43393605/how-to-make-a-swift-class-singleton-instance-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!