首页 > 解决方案 > 将默认数据库路径更改为组路径后,iOS RealmSwift 不会更新模型

问题描述

我已经在我的应用程序中使用领域一段时间了。现在我已经向应用程序添加了共享扩展,我注意到我需要为组子目录定义领域默认文件路径,以便我可以从应用程序和扩展程序访问同一个数据库。我搜索了几次,我在这里找到了最好的解决方案,并在这里帮助下。

这是我的 AppDelegate 文件

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // migrateRealm()
    // configRealm()

    return true
}

private func configRealm() {

    let fileURL = FileManager.default
        .containerURL(forSecurityApplicationGroupIdentifier: "group.com.hjri.khandehland")!
        .appendingPathComponent("Library/Caches/default.realm")

    let config = Realm.Configuration(fileURL: fileURL)

    Realm.Configuration.defaultConfiguration = config
}

private func migrateRealm() {
    let fileManager = FileManager.default

    let originalDefaultRealmURL = Realm.Configuration.defaultConfiguration.fileURL
    //Cache original realm path (documents directory)
    let originalDefaultRealmPath = originalDefaultRealmURL?.path

    //Generate new realm path based on app group
    let realmURL = FileManager.default
        .containerURL(forSecurityApplicationGroupIdentifier: "group.com.hjri.khandehland")!
        .appendingPathComponent("Library/Caches/default.realm")

    let realmPath = realmURL.path

    if originalDefaultRealmPath != nil {
        //Moves the realm to the new location if it hasn't been done previously
        if (fileManager.fileExists(atPath: originalDefaultRealmPath!) && !fileManager.fileExists(atPath: realmPath)) {

            print("***** FILE EXISTS AND MOVING")
            do {
                try fileManager.moveItem(atPath: originalDefaultRealmPath!, toPath: realmPath)
            } catch {
                print("***** REALM FILE PATH MIGRATION ERROR *****")
            }
        } else {
            print ("***** FILE DOES NOT EXIST *****")
        }
    }

    //Set the realm path to the new directory

    Realm.Configuration.defaultConfiguration.fileURL = realmURL
}

另外,我的模型类是

class User: Object {
    @objc dynamic var username: String = ""
    @objc dynamic var email: String = ""
    @objc dynamic var password: String = ""
    @objc dynamic var accessToken: String = ""
    @objc dynamic var refreshToken: String = ""
}
class Message: Object {
    @objc dynamic var id: Int = 0
    @objc dynamic var content: String = ""
    @objc dynamic var submitDate: String = ""
    @objc dynamic var submitDateEpoch: Double = 0
    @objc dynamic var favoriteCount:Int = 0
    @objc dynamic var isFavorite: Bool = false
    @objc dynamic var needsSync: Bool = false
    @objc dynamic var syncDetails: String = ""
    @objc dynamic var isNew: Bool = true
}

为了首先测试我的应用程序,我使用默认领域文件路径使用模型,然后我取消注释其中一个migrateRealm()configRealm()任何方法都不能正常工作,在取消注释第一个之后,我可以登录(创建用户实例)和重新启动应用程序后,它会正确读取用户数据,但消息根本不会出现在应用程序中,这意味着在读取/写入它们时存在问题,取消注释时configRealm应该只更改领域路径并且不要迁移旧数据,该应用程序仍然向我显示旧消息,但它不会加载用户,这意味着我的登录状态在重新启动后消失了,而且如果我更新消息属性,使领域更改消息模型属性,它引发此错误并且应用程序崩溃:

* 由于未捕获的异常“RLMException”而终止应用程序,原因:“尝试在写入事务之外修改对象 - 首先在 RLMRealm 实例上调用 beginWriteTransaction。” *首先抛出调用栈

这个错误表明我在领域写闭包之外进行更新操作,但我的代码在更改路径之前运行良好,而且我确实在写块内编写了更新命令,如您在此处看到的,这是我的消息更新方法

func update(content: String? = nil, isFavorite: Bool? = nil, needsSync: Bool? = nil, syncDetails: String? = nil, favoriteCount: Int? = nil) {
    let realm = try! Realm()
    try! realm.write {
        self.content = content ?? self.content
        self.isFavorite = isFavorite ?? self.isFavorite
        self.needsSync = needsSync ?? self.needsSync
        self.syncDetails = syncDetails ?? self.syncDetails
        self.favoriteCount = favoriteCount ?? self.favoriteCount
    }
}

我不知道是我弄错了还是领域问题或XCode问题(我使用的是测试版)此刻非常困惑

我使用 Realm 3.7.5 XCode 10 Beta

标签: iosswiftxcoderealmshare-extension

解决方案


我通过在每次调用它时将我的自定义配置设置为 Realm 实例来使它工作,我通过制作这个计算属性并在我想使用 Realm 的任何时候调用它变得更容易

static var realmInstance: Realm {

    let fileURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: groupIdentifier)!.appendingPathComponent(databaseFileName)

    var config = Realm.Configuration(fileURL: fileURL)

    return try! Realm(configuration: config)
}

推荐阅读