Search code examples
swiftsqlitefmdb

"unexpectedly found nil while unwrapping an Optional value" error when returning a row in SQLite DB


I have integrated the FMDB Sqlite Wrapper into my iOS application and I have written a couple of DB functions, that have all worked perfectly until now.

I used the same approach for a simple method that is supposed to return a single element in a Resultset item, but I get the above error. There is nothing different in the logic from the other methods so I have no idea why the error occurs and why it happens on both lines with stringForColumn and not in the line with intForColumn (as the debugger tells me).

Any help or tips would be greatly appreciated!

func fetchExercise(exerciseId: Int) -> Exercise {
    sharedInstance.database!.open()
    let resultSet: FMResultSet! = sharedInstance.database!.executeQuery("Select * from Exercises where ExerciseId = ?", withArgumentsInArray: [String(exerciseId)])
    let fetchedExercise: Exercise = Exercise()
    if (resultSet != nil) {
        fetchedExercise.exerciseId = Int(resultSet.intForColumn("ExerciseId"))
        fetchedExercise.exerciseCategory = resultSet.stringForColumn("ExerciseCategory")
        fetchedExercise.exerciseTitle = resultSet.stringForColumn("ExerciseTitle")
    }
    sharedInstance.database!.close()
    return fetchedExercise      
}

The resultSet is as follows:


Solution

  • You have to call resultsSet.next() to retrieve the results. For example:

    func fetchExercise(exerciseId: Int) -> Exercise {
        sharedInstance.database!.open()
        defer { sharedInstance.database!.close() }
    
        let resultSet = try! sharedInstance.database!.executeQuery("Select * from Exercises where ExerciseId = ?", values: [exerciseId])
        let fetchedExercise = Exercise()
        if resultSet.next() {
            fetchedExercise.exerciseId       = resultSet.longForColumn("ExerciseId")
            fetchedExercise.exerciseCategory = resultSet.stringForColumn("ExerciseCategory")
            fetchedExercise.exerciseTitle    = resultSet.stringForColumn("ExerciseTitle")
        }
    
        return fetchedExercise
    }
    

    BTW, I'm not sure why you're converting exerciseId to a string in the query. I'd personally just pass the Int value, as shown above.