【问题标题】:Swift: App crashes when accessing NULL value from SQLite.swiftSwift:从 SQLite.swift 访问 NULL 值时应用程序崩溃
【发布时间】:2018-08-15 08:44:23
【问题描述】:

我刚开始学习 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.

注意: 我试过禁用优化级别(构建设置),结果是一样的。

我将不胜感激帮助或解决方案!

【问题讨论】:

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


    【解决方案1】:

    您需要告诉 SQLite.swift medium 列可以使用可选的泛型 &lt;String?&gt; 为空

    改变

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-10
      • 2014-04-11
      相关资源
      最近更新 更多