How to make a stream of Swift Class Singleton instances safe?

I have a singleton class:

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 execute the function inside the class. However, when I access an instance from another thread, it throws fancy results, as if it were trying to create another instance. Should I refer to an instance in the same thread?

To clarify that fancy results show database I / O errors due to two instances trying to access db right away

Refresh
refer to this question for more information on the database code: Using transactions to insert are errors loading Sqlite.swift

+5
source share
2 answers
 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! } } 

USAGE: let object: ClassName = ClassName.shareInstance

Swift 3.0

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

USAGE: let object: ClassName = ClassName.shareInstance

+5
source

In Swift 3.0, add a private init so that other users do not use the default initializer ().

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

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


All Articles