Swift:从SQLite.swift访问NULL值时,应用程序崩溃

时间:2018-08-15 08:44:24

标签: ios swift swift4 sqlite.swift xcode9.4

我刚刚开始学习Swift4。我已经阅读了有关堆栈溢出重复问题的所有建议,但无法解决或理解我的问题。

我正在从SQLite.swift数据库中获取数据:

ViewController.swift:

import Foundation
import SQLite

// Load DB with SQLite.swift
let path = Bundle.main.path(forResource: "myDataBaseFile", ofType: "sqlite")!
let db = try! Connection(path, readonly: true)

// SQLite.swift define table
let table = Table("table")

// SQLite.swift define columns 
let id = Expression<Int>("id")
let medium = Expression<String>("medium")

// Function to get query result
func queryForMedium(idForQuery: Int) -> String? {
    let media = try? db.scalar(table.select(medium).filter(id == idForQuery))
    return media
}

// ViewDidLoad
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // Value for ID = 2 access a SQL Null value
    anOptionalString = queryForMedium(idForQuery: 2)

    if anOptionalString != nil {
        print("Contains a value!")
    } else {
        print("Doesn’t contain a value.")
    }

}

结果:

  • ID = 1包含“测试”->应用运行:控制台输出:
    Contains a value!
  • ID = 2包含 NULL -> CRASH :控制台输出:
    SQLite was compiled with optimization - stepping may behave oddly; variables may not be available.

Xcode Screenshot after App Crash

注意: 我尝试禁用Optimazion Level(构建设置),结果相同。

感谢您的帮助或解决方案!

1 个答案:

答案 0 :(得分:1)

您需要通过使用可选的泛型medium告诉SQLite.swift <String?>列可以为空

更改

let medium = Expression<String>("medium")

let medium = Expression<String?>("medium")