0

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


}
SiHa
  • 7,830
  • 13
  • 34
  • 43
MK DEV
  • 64
  • 10

1 Answers1

2

A shared instance used as singleton must be static

static let shareInstance = DatabaseManager()
vadian
  • 274,689
  • 30
  • 353
  • 361
  • The Bad_Exec error code 2 has been resolved but i don't get the array they are still empty ! infect connection made successfully and i debug it at sharedInstance point they fetch all the records but after iterating to the loop there is no data :( – MK DEV Nov 15 '16 at 11:24