2016-11-15 44 views
0

當我試圖使用單例在swift中獲取SQLite數據庫中的所有數據時,我在sharedInstance中收到一個錯誤,並且提取了零個結果。Singleton中的錯誤使用SQLite Swift

這是我的代碼:

DatabaseManager.swift

import SQLite 

class DatabaseManager { 


    let shareInstance = DatabaseManager() 
    let recipeTable = Table("recipes") 
    let id = Expression<String>("id") 
    let title = Expression<String>("title") 
    let category = Expression<String>("category") 
    let recipe = Expression<String>("recipe") 
    let bookmark = Expression<String>("Bookmark") 

    let db: Connection = { 
     let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! 
     return try! Connection("\(path)/recipe.sqlite") 
    }() 

    func findAll() -> Array<foodRecipe>{ 
     var foodRecipeArray = [foodRecipe]() 

     do{ 
     //for row in try db.prepare(recipeTable.select(id,title,recipe,category,bookmark).filter(category == "appetizers")){ 
     for row in try shareInstance.db.prepare(recipeTable){ 
      let fd = foodRecipe() 
      fd.id = row[id] 
      fd.title = row[title] 
      fd.recipe = row[recipe] 
      fd.category = row[category] 
      fd.bookmark = row[bookmark] 
      foodRecipeArray.append(fd) 
     } 

     } 
     catch let error as NSError { 
      print("Error: \(error.description)") 
     } 
     return foodRecipeArray 
    } 
} 

AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 

    var foodRecipeArray: [foodRecipe] 

    let dbMngr: DatabaseManager = DatabaseManager() 

    foodRecipeArray = dbMngr.findAll() 

    print("Food Recipe Array Count: \(foodRecipeArray.count)") //return 0 


    print("Food Recipe Array: \(foodRecipeArray)") //result nil 


    // Override point for customization after application launch. 
    return true 


} 

回答

2

共享實例用作單必須static

static let shareInstance = DatabaseManager() 
+0

Bad_Exec錯誤代碼2已解決,但我沒有得到數組,它們仍然是空的!感染連接成功,我在sharedInstance調試它們獲取所有記錄,但迭代到循環後沒有數據:( –