iOS-Swift 数据库 WCDB 二次封装使用/自定义字段映射类型

WCDB官方使用文档

WCDB简介

WCDB 是一个易用、高效、完整的移动数据库框架,它基于 SQLite 和 SQLCipher 开发,在微信中应用广泛,且支持在 C++、Java、Kotlin、Swift、Objc 五种语言环境中使用。

整体架构:

对于WCDB详细的介绍和使用请移步官方文档,本篇文章主要是对WCDB 常用的功能进行二次封装,使数据库的操作更方便一些。还有就是对于自定义映射类型的详细使用,作为官方文档在这块的一个补充。

安装
其它方式安装

通过 Cocoapods 安装

复制代码
    pod 'WCDB.swift'

二次封装

DBmanager

c 复制代码
import Foundation
import WCDBSwift

struct WcdbDataPath {
    static let basePath =  NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/DB/wcdb.db"
}

//表名
enum DBTableName : String {
    case userTable = "userTable"
}

class DBmanager{
    static let share = DBmanager.init()
    var db: Database?
    init() {
        db = createDB()
        createTable()
    }
    
    private func createDB() -> Database {
        return Database(at: WcdbDataPath.basePath)
    }
    
    /// 数据库与表的初始化
    private func createTable() {
        do {
            //1. 创建主数据库main的相关表
            try db?.run(transaction: { _ in
                self.createTable(table: DBTableName.userTable, modelType: UserModel.self)
            })
            
        } catch let error {
            debugPrint("初始化数据库及ORM对应关系建立失败\(error.localizedDescription)")
        }
    }
    
    
    ///创建表
    private func createTable<T: TableDecodable>(table: DBTableName, modelType: T.Type) {
        do {
            try db?.create(table: table.rawValue, of: modelType)
        }catch let error {
            debugPrint(error.localizedDescription)
        }
    }
    
    ///插入数据
    public func inser<T: TableEncodable>(objects:[T], intoTable table: DBTableName){
        do {
            try db?.insert(objects, intoTable: table.rawValue)
        }catch let error {
            debugPrint(error.localizedDescription)
        }
    }
    
    ///修改
    public func update<T: TableEncodable>(fromTable table: DBTableName, on propertys:[PropertyConvertible], itemModel object:T,where condition: Condition? = nil){
        do {
            try db?.update(table: table.rawValue, on: propertys, with: object, where: condition)
        } catch let error {
            debugPrint(" update obj error \(error.localizedDescription)")
        }
    }
    
    ///删除
    public func deleteFromDb(fromTable table: DBTableName, where condition: Condition? = nil){
        do {
            try db?.delete(fromTable: table.rawValue, where:condition)
        } catch let error {
            debugPrint("delete error \(error.localizedDescription)")
        }
    }
    
    ///查询
    public func qurey<T: TableDecodable>(fromTable table: DBTableName, where condition: Condition? = nil, orderBy orderList:[OrderBy]? = nil) -> [T]? {
        do {
            let allObjects: [T] = try (db?.getObjects(fromTable: table.rawValue, where:condition, orderBy:orderList))!
            debugPrint("\(allObjects)");
            return allObjects
        } catch let error {
            debugPrint("no data find \(error.localizedDescription)")
        }
        return nil
    }
    
    ///删除数据表
    func dropTable(table: DBTableName) -> Void {
        do {
            try db?.drop(table: table.rawValue)
        } catch let error {
            debugPrint("drop table error \(error)")
        }
    }
    
    /// 删除所有与该数据库相关的文件
    func removeDbFile() -> Void {
        do {
            try db?.close(onClosed: {
                try self.db?.removeFiles()
            })
        } catch let error {
            debugPrint("not close db \(error)")
        }
    }
}

使用

新建一张表

  1. 在枚举中新增表名
c 复制代码
//表名
enum DBTableName : String {
    case userTable = "userTable"
}
  1. 新建model
    示例model
c 复制代码
import Foundation
import WCDBSwift

final class UserModel: TableCodable {
 
    var id: Int = 0
    var name: String = ""
    var height: Double = 0.0
      
    enum CodingKeys: String, CodingTableKey {
        typealias Root = UserModel
        static let objectRelationalMapping = TableBinding(CodingKeys.self)
        case id
        case name
        case height
    }
    
}
  1. 新建表

数据库操作

首先创建数据库对象

c 复制代码
  let commonDB = DBmanager.share

新增

c 复制代码
      let model = UserModel()
        model.id = 1
        model.name = "张三"

commonDB.inser(objects: [model], intoTable: .userTable)

删除

c 复制代码
 commonDB.deleteFromDb(fromTable: .userTable, where: UserModel.Properties.id.is(model.id))

修改

复制代码
// 创建要更新的 UserModel 对象
var userToUpdate = UserModel()
userToUpdate.name = "NewName"
userToUpdate.height = 180.0

// 定义要更新的属性
let propertiesToUpdate = [UserModel.Properties.name, UserModel.Properties.height]

// 构建条件(例如,根据 id 更新)
let updateCondition = UserModel.Properties.id == 1

// 调用 update 方法
commonDB.update(fromTable: .userTable, on: [UserModel.Properties.height], itemModel: userToUpdate,where: updateCondition)

查询

复制代码
if let tempArray:[UserModel] = commonDB.qurey(fromTable: .userTable) {
            userArray = tempArray
        }

自定义字段映射类型

自定义字段映射类型文档

示例

复制代码
import Foundation
import WCDBSwift

final class UserModel: TableCodable {
 
    var id: Int = 0
    var name: String = ""
    var height: Double = 0.0
    var address: addressModel?
    
    enum CodingKeys: String, CodingTableKey {
        typealias Root = UserModel
        static let objectRelationalMapping = TableBinding(CodingKeys.self)
        case id
        case name
        case height
        case address
    }
    
}

//自定义字段映射类型
class addressModel: ColumnCodable {
    
    required init() {}
    
    var home:String = ""
    var company:String = ""

    static var columnType: ColumnType {
           return .BLOB
       }
    
    required init?(with value: WCDBSwift.Value) {
        let data = value.dataValue
        guard data.count > 0,
              let jsonDict = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
            return nil
        }
        
        guard let home = jsonDict["home"] as? String else {
            return nil
        }
        guard let company = jsonDict["company"] as? String else {
            return nil
        }
        
        self.home = home
        self.company = company
    }
    
    func archivedValue() -> WCDBSwift.Value {
        var jsonDict: [String: Any] = [:]
        jsonDict["home"] = home
        jsonDict["company"] = company
        guard let data = try? JSONSerialization.data(withJSONObject: (jsonDict as NSDictionary), options: []) else {
            return FundamentalValue.init()
        }
        
        return FundamentalValue.init(data)
    }
    
}

结语

以上便是WCDB Swift 版本的基本使用,本篇旨在帮你快速的上手使用WCDB来完成数据库的基础操作。如需其它高级的数据库操作,请移步到官方文档。

WCDB仓库地址
WCDB官方文档直通车


感谢您的阅读和参与,HH思无邪愿与您一起在技术的道路上不断探索。如果您喜欢这篇文章,不妨留下您宝贵的赞!如果您对文章有任何疑问或建议,欢迎在评论区留言,我会第一时间处理,您的支持是我前行的动力,愿我们都能成为更好的自己!

相关推荐
睡不醒男孩0308235 分钟前
第四篇:数据库国产化与信创替代的守护者:基于CLup的异构数据库一站式运维平台构建
运维·数据库·金融·clup·中启乘数
Lumistory6 分钟前
2026年城市照明工程4大核心痛点及解决方案
大数据·数据库
2501_9160074713 分钟前
iOS 开发工具选择指南 从编辑器、编译器到自动化构建
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
岳麓丹枫00116 分钟前
PG数据库无法接受连接问题分析定位
数据库·postgresql
JdSnE27zv31 分钟前
SQLite内存数据库
数据库·sql·sqlite
SelectDB技术团队32 分钟前
预约发布会|核心产品力首发,如何构建面向 Agent 时代的企业级数据引擎
数据库·数据仓库·人工智能·数据分析·可观测·apache doris·selectdb
2601_9618451538 分钟前
2026四级作文预测题|英语四级写作押题+提纲PDF
java·c语言·数据库·c++·python·pdf·php
计算机安禾40 分钟前
【数据库系统原理】第13篇:现实世界的概念抽象:实体-联系模型向关系模型的转化策略
数据库
库奇噜啦呼1 小时前
【iOS】源码学习-YYModel源码学习
学习·ios·cocoa
JAVA面经实录9171 小时前
NoSQL 非关系型数据库【简洁版】
java·数据库·nosql