Sqlite.swift: Singleton for connection

Created on 13 Oct 2015  路  4Comments  路  Source: stephencelis/SQLite.swift

Now that I migrated the project to swift 2 I have a question about the connection to the database. I read that for every connection there is be used a different thread. I have datahelper classes for my 15 tables. Every of this classes has a structure like

let settings: Settings = Settings()
static let db = try! Connection(Settings.getDatabase())
static let TABLE_NAME = "work"
static let db_id = Expression("id")
static let db_task_id = Expression("task_id") ...

Obviously so every datahelper makes his own connection. It would be better to wrap the connection in a class and use a sinlgeton? If yes, perhaps someone can give me some hint.

Thanks
Arnold

question

Most helpful comment

If you're not adding any logic beyond a reference, you can use a closure for configuration and define it in your top-level module (app):

let db: SQLite.Connection = {
    let path = NSSearchPathForDirectoriesInDomains(
        .DocumentDirectory, .UserDomainMask, true
    ).first!
    return try! Connection("\(path)/db.sqlite3")
}()

All 4 comments

import Foundation

import SQLite

class SQLiteDataStore {

static let sharedInstance = SQLiteDataStore()

var FRDB: Connection

private init() {



        let dirPaths =  NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true)
        let docsDir = dirPaths[0]

        let path = (docsDir as NSString).stringByAppendingPathComponent("myDbase.sqlite")



        FRDB = try! Connection(path)

}

}

In the helper class

//DB Connection

 static let connectToDB = SQLiteDataStore.sharedInstance.FRDB

If you're not adding any logic beyond a reference, you can use a closure for configuration and define it in your top-level module (app):

let db: SQLite.Connection = {
    let path = NSSearchPathForDirectoriesInDomains(
        .DocumentDirectory, .UserDomainMask, true
    ).first!
    return try! Connection("\(path)/db.sqlite3")
}()

Closing out unless you have a bug to report! Please ask a question on StackOverflow if you have more questions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Chepond picture Chepond  路  3Comments

kartikthapar picture kartikthapar  路  4Comments

Tchoupinax picture Tchoupinax  路  8Comments

fortitude1990 picture fortitude1990  路  4Comments

DiamondYuan picture DiamondYuan  路  3Comments