ios - 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?
提前致谢。
解决方案
推荐阅读
- redis - Redis 5.0.11 内存碎片率高
- python - VaulueError:解包的值太多(预期为 2)Django 3.2.5
- mysql - 如何使用 SQL 获取用户不存在的计数项目
- swift - 点击手势识别器 Xcode
- c# - 我想在我的配置文件(ASP.NET / C#)中存储类名
- coldfusion - 使用 Coldfusion 从 DB 中自动填充表单字段
- python - python - 如何使用熊猫将pyqt中的图表类型更改为区域图或条形图?
- c# - 提高 Linq to SQL 列表交集的性能
- couchbase - 沙发库中的 JSON 键前缀和值搜索
- node.js - 如何在 aws lambda 中存档使用 Node.js 挂载 EFS 的目录