简单点, 直接点, 暴力点
1. 封装 ArrayObjectRealm
管理类
import Foundation
import RealmSwift
// 元素为对象的数组存储
open class ArrayObjectRealm<T: Object>: RealmManager {
// 增
open func insert(_ t: T) {
try? realm.write {
realm.add(t)
}
}
// 删
open func delete(_ t: T) {
try? realm.write {
realm.delete(t)
}
}
// 删除所有
open func deleteAll() {
try? realm.write {
for item in allValue() {
realm.delete(item)
}
}
}
// 更新
open func update(t: T,_ callback: (T) -> ()) {
try? realm.write{ callback(t) }
}
// 查所有对象
open func allValue() -> [T] {
var ts: [T] = []
realm.objects(T.self).forEach { t in
ts.append(t)
}
return ts
}
// 查某个主键值为'key'的对象
open func value(from key: String) -> T? {
return realm.object(ofType: T.self, forPrimaryKey: key)
}
}
2. 创建 数组元素模型:
import RealmSwift
import ObjectMapper
public class FileModel: Object, Mappable {
// 文件名称
@Persisted public var name = ""
// 文件创建时间
@Persisted public var date = Date()
// 第二名称
@Persisted public var secondName = ""
// 设置主键
public override class func primaryKey() -> String? {
return "name"
}
public override init() {
super.init()
}
/// 以下两个函数为ObjectMapper 协议方法
public required init?(map: ObjectMapper.Map) { }
public func mapping(map: ObjectMapper.Map) {
name <- map["name"]
date <- map["date"]
secondName <- map["secondName"]
}
}
3. 创建需要存储的数组对象FileModel
管理类, 继承自ArrayObjectRealm
import RealmSwift
import Foundation
public class FilesManager: ArrayObjectRealm<FileModel> {
// 单例访问
public static let shared = FilesManager()
// 数组, 方便访问
public var files: [FileModel] = []
public override init() {
super.init()
files = allValue()
}
/// 给数组插入新对象
public override func insert(_ t: FileModel) {
super.insert(t)
files = allValue()
}
/// 删除数组中指定对象
public override func delete(_ t: FileModel) {
super.delete(t)
files = allValue()
}
/// 删除数组中指定对象
public override func deleteAll() {
super.deleteAll()
files = allValue()
}
/// 更新数组中某个对象
public override func update(t: FileModel, _ callback: (FileModel) -> ()) {
super.update(t: t, callback)
files = allValue()
}
/// 通过主键过去某个对象
public override func value(from key: String) -> FileModel? {
return super.value(from: key)
}
}
4. 使用
请点击打开 示例demo 查看: Example/Database/ViewController.swift
文件