這是方法,我拿這可能給你的洞察力。我有程序中的數據庫調用,但表格方法(創建,添加,更新)在一個類中,並且在需要時被多次調用。
所以創建一個數據庫我呼籲,在這種情況下,當按下按鈕:
@IBAction func buttonCreateTable(sender: AnyObject) {
var locationRecord: LocationRecord = LocationRecord()
var isCreated = DatabaseFunctions.instance.createLocationTable()
if isCreated {
NSLog("Locations Database Created")
} else {
NSLog("Locations Database Not Created")
}
}
類,DatabaseFunctions.swift,會讀...
import UIKit
let sharedInstance = DatabaseFunctions()
class DatabaseFunctions: NSObject {
var database: FMDatabase? = nil
class var instance: DatabaseFunctions {
sharedInstance.database = FMDatabase(path: Utilities.getPath("yourDatabase.sqlite"))
var path = Utilities.getPath("yourDatabase.sqlite")
return sharedInstance
}
// yourTableFunctions *************************
func createLocationTable() -> Bool {
sharedInstance.database!.open()
let sqlStatement = "CREATE TABLE IF NOT EXISTS MYTABLE (ID INTEGER PRIMARY KEY AUTOINCREMENT, TIMESTAMP DATETIME DEFAULT CURRENT_TIMESTAMP, TIMESTAMPLASTEDIT DATETIME DEFAULT CURRENT_TIMESTAMP, NAME TEXT, nil)"
let isCreated = sharedInstance.database!.executeUpdate(sqlStatement, withArgumentsInArray:nil)
sharedInstance.database!.close()
return isCreated
}
}
LocationsRecord在另一個快速的LocationInfo.swift文件中分開保存,例如:
import UIKit
// Locations Class
class LocationRecord: NSObject {
var locationSelected : Int32 = Int32()
var locationRecordNo : Int32 = Int32()
var locationName: String = String()
}
你有沒有想過這個?我也有同樣的問題。 – thumbtackthief
不,我仍然這樣做,如果db.open(){/ *做的東西*/db.close()} –