首页 > 解决方案 > NSMergeConflict 与 oldVersion 和 newVersion 报告为相等

问题描述

我最近设法在我的代码中捕获了一个极其罕见的异常,并希望这里的人们可以帮助我理解它。我有一个游戏,它正在跟踪经过的时间并每秒将值保存到 Core Data。同时,用户可能正在玩游戏并导致分数更新,这也保存在 Core Data 中。我怀疑我应该序列化保存,但目前我不是。99.99% 的时间里,一切都很好,但偶尔调用会context.save()引发异常。

我有一个合并策略设置如下:

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

这就是我节省时间的方法。相同的模式用于更新玩家的分数。

func saveElapsedTime() {
    let container = (UIApplication.shared.delegate as! AppDelegate).persistentContainer
    container.performBackgroundTask() { (context) in
        let storedGame = context.object(with: self.storedGameID) as! StoredGame
        storedGame.elapsedTime = Int32(self.elapsedTime)

        do {
            try context.save()
        } catch let nserror as NSError {
            print("saveElapsedTime: failed to save: \(nserror). userInfo: \(nserror.userInfo).")
        }
    }
}

我能够捕捉到的罕见错误如下所示:

Error Domain=NSCocoaErrorDomain Code=133020 "Could not resolve merge changes."
<snip>...with oldVersion = 463 and newVersion = 463...<snip>

我看过很多帖子,旧版本和新版本相差一个或一小部分,人们建议设置与默认值不同的合并策略。我猜在我的情况下 oldVersion == newVersion 这是因为多个线程试图同时保存。有人可以通过查看错误消息来确认这一点吗?我是否应该像本例中那样使用 OperationQueue 序列化所有保存:NSPersistentContainer concurrency for save to core data

提前致谢。

标签: iosswiftcore-data

解决方案


推荐阅读