MK DEV MK DEV - 20 days ago 10
Swift Question

Error in Singleton usng SQLite Swift

When I am trying to fetch all the data in the SQLite Database in swift using singleton, I get an error in sharedInstance and zero results are fetched.

Here is my code:

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


}

Answer

A shared instance used as singleton must be static

static let shareInstance = DatabaseManager()
Comments