如何从iOS SQLite数据库保存和获取数据?

时间:2019-12-10 16:31:00

标签: swift sqlite decodable

我想从数据库中获取“ label”和“ slug”字符串。它们在init中的打印效果很好(来自解码器:解码器),但是在保存它们时我可能做错了,因为其他地方都没了。

这是我的可腐烂课程

   
import Foundation
import SQLite

final class AdditionalField : Decodable {

    var label : String?
    var slug : String?
    var data: Any?
    var type: QuestionType?
    var pollQuestion: PollQuestion?

    enum CodingKeys: String, CodingKey {
        case label = "label"
        case slug = "slug"
    }

    required init(from row: Row) {
        label = row[Columns.label]
        slug  = row[Columns.slug]

        if let dataString = data as? String, let data = dataString.data(using: .utf8) {
            self.data = type?.create(from: data)
        }
    }

    required  init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        label = try values.decodeIfPresent(String.self, forKey: .label)
        print(label!)
        print("label")

        slug = try values.decodeIfPresent(String.self, forKey: .slug)
        print(slug!)
        print("slug")
    }
}


extension AdditionalField: SQLTable {

    static var tableName = "AdditionalField"

    enum Columns {
        static let label = Expression<String>("label")
        static let slug = Expression<String>("slug")
    }


    static func createTable(db: Connection) throws {
        try db.run(table.create(ifNotExists: true) { table in
            table.column(Columns.label)
            table.column(Columns.slug)
        })
    }

    static func insert(elements: [AdditionalField]) throws {
        try Database.shared.insert(elements: elements)
    }

    func insert(db: Connection) throws {
        try db.run(AdditionalField.table.insert(or: .replace, [
            Columns.label <- label ?? "",
            Columns.slug  <- slug ?? ""
        ]))
    }

}

我试图那样使用它们。也许这是问题所在?

//   let field = additionalFields?.filter{$0.label == anyTextField.placeholder}.first

       // anyTextField.placeholder = field?.label

1 个答案:

答案 0 :(得分:0)

我创建了一个名为SundeedQLite

的库

随时尝试!