ios - 快速地,有没有办法从第二个 Realm 包添加新数据,而不覆盖当前默认 Realm 中的任何现有数据?

标签 ios swift realm bundle overwrite

首次加载应用程序时, bundle Realm (Realm1) 将被复制到文档文件夹中。现在, bundle Realm 已设置为默认 Realm ,我可以更新 bool 属性,以便 TableView 可以显示标记和未标记的单元格。不过,我正在寻找一种将第二个 Realm (Realm2) 与后续更新 bundle 在一起的方法,这会将新数据添加到现有的默认 Realm ,但不会覆盖当前的默认 Realm 。我目前正在使用 swift 5 和 Xcode 11.1,如果这有帮助的话。

到目前为止,我唯一能想到的就是添加代码块以将新条目添加到默认 Realm 。首先, View 将检查 Realm 的计数,如果计数与原始包相同,那么它将添加新数据,如果计数等于初始包加上新条目,那么它会添加新数据。不会再次添加新数据。我希望有一个在我看来更简单、更干净的解决方案。

理想情况下,最终结果是一种更新现有默认 Realm 的方法,而不覆盖已编辑的内容。尽管我对使用 Realm 相当陌生,但任何为我指明解决方案正确方向的帮助将不胜感激。谢谢。

下面附有我实现的用于从 bundle 加载默认 Realm 的当前代码。



    let bundlePath = Bundle.main.path(forResource: "preloadedData", ofType: "realm")!
            let defaultPath = Realm.Configuration.defaultConfiguration.fileURL!.path
            let fileManager = FileManager.default

    //        Copy Realm on initial launch
            if !fileManager.fileExists(atPath: defaultPath){
                do {
                    try fileManager.copyItem(atPath: bundlePath, toPath: defaultPath)
                    print("Realm was copied")
                } catch {
                    print("Realm was not coppied \(error)")
                }
            }
            return true

最佳答案

在磁盘上创建默认 Realm 后,如果您想从 bundle 的 Realm 中读取数据,请使用以下代码

    let config = Realm.Configuration(
        // Get the URL to the bundled file
        fileURL: Bundle.main.url(forResource: "MyBundledData", withExtension: "realm"),
        // Open the file in read-only mode as application bundles are not writeable
        readOnly: true)
    let realm = try! Realm(configuration: config)

读取数据后,您可以切换回来

var config = Realm.Configuration()
config.fileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("\(some_realm_name).realm")
Realm.Configuration.defaultConfiguration = config

只要不覆盖,请确保您的对象使用唯一的主键,并且在写入时,不会覆盖任何内容,因为对象将添加唯一的主键而不是覆盖。

class MyClass: Object {
    @objc dynamic var my_primary_id = NSUUID().uuidString

关于ios - 快速地,有没有办法从第二个 Realm 包添加新数据,而不覆盖当前默认 Realm 中的任何现有数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58417998/

相关文章:

swift - 为什么我的 SKSpriteNode 可以工作,但只是暂时的

swift - 是否可以从其共享扩展访问应用程序的 RealmSwift DB?

ios - 如何在 Realm 数组的特定索引处插入对象?

ios - 没有 Storyboard的自定义 TableViewCell

ios - Swift 将 json 解析为结构体

React-Native Realm 通过主键获取

iPhone : How to separate string like "ListName|Definition|Answer"

ios - ios中的Pubnub使用什么密码和 key

iphone - 当我最小化 iPhone 中的任何应用程序时,该应用程序是否在后台运行?或暂停?或停止应用程序?

ios - 崩溃后的 Xcode 错误