- 模型绑定
- 创建数据库与表
- 操作数据
模型绑定
WCDB 基于 Swift 4.0 的 协议实现模型绑定的过程。
对于已经存在的 Sample
类:
- class Sample: TableCodable {
- var identifier: Int? = nil
- var description: String? = nil
- enum CodingKeys: String, CodingTableKey {
- static let objectRelationalMapping = TableBinding(CodingKeys.self)
- case identifier
- case description
- }
- }
这部分代码基本都是固定模版,暂时不用理解其每一句的具体含义,我们会在模型绑定一章中进行进一步介绍。
创建数据库与表
One line of code 是 WCDB 接口设计的一个基本原则,绝大部分的便捷接口都可以通过一行代码完成。
创建数据库表
- // 以下代码等效于 SQL:CREATE TABLE IF NOT EXISTS sampleTable(identifier INTEGER, description TEXT)
- try database.create(table: "sampleTable", of: Sample.self)
对于已进行模型绑定的类,同样只需一行代码完成。
操作数据
基本的增删查改同样是 One line of code
查找操作
- let objects: [Sample] = try database.getObjects(fromTable: "sampleTable")