RealmManager
使用 Realm Mobile Database 以线程化和更简单的方式持久化数据
使用 RealmSwift
安装
CocoaPods
CocoaPods 是 Cocoa 项目的依赖管理器。您可以使用以下命令安装它
$ gem install cocoapods
需要 CocoaPods 1.9.1+ 才能构建 RealmManager 4.3.0+。
要使用 CocoaPods 将 RealmManager 集成到您的 Xcode 项目中,在您的 Podfile
中指定它
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '12.0'
use_frameworks!
target '<Your Target Name>' do
pod 'RealmManager', '~> 4.3.0'
end
然后,运行以下命令
$ pod install
手动
如果您不想使用上述任何依赖关系管理器,您可以将RealmManager手动集成到项目中。
使用方法
初始化
您可以在初始化期间明确指定将管理的对象类型。
//Object must be a subclass of Realm.Object
let manager = RealmManager<Object> = RealmManager(configuration: nil,
fileUrl: nil)
向现有模型添加或更新对象
您可以使用此方法向现有模型添加或更新对象。
注意:本代码库假设每个对象都是唯一的,因此模型需要具有一个主键
//object must be a subclass of Realm.Object
RealmManager.addOrUpdate(object: object,
completion: { (error) in
//Code goes here
})
或者如果您需要为您的Realm实例进行配置
var config = Realm.Configuration()
let directory: URL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier:
"group.com.directurl")!.appendingPathComponent("db.realm")
config.fileURL = directory
//Foo must subclass to Realm.Object
let foo = Foo(description:"Bar")
RealmManager.addOrUpdate(configuration: config,
object: foo,
completion: { (error) in
//Code goes here
})
对象可以是Object
、Array
、Dictionary<AnyHashable,AnyObject>
或AnyObject
的实例。
获取
从Realm数据库中获取对象
//Foo must subclass to Realm.Object
let foo = Foo(description:"Bar")
RealmManager.fetch(condition: "description == '\(foo.description)'",
completion: { (result) in
//Your code can do anything with 'result' >:)
})
删除
通过谓词映射和删除对象
RealmManager.delete(object: nil,
condition: "description = \(foo.description)",
completion: { (error) in
//Code goes here
})
或者,如果您有对象但不需要映射它
RealmManager.deleteObject(object: foo,
completion: { (error) in
//Code goes here
})
作者
markcdb,[email protected]
许可证
RealmManager可在MIT许可证下使用。更多信息请参阅LICENSE文件。