问题描述
我的应用有一个可重现的 CoreData 错误。
我使用 viewContext
进行显示,使用 backgroundContext
进行对象更新。两个上下文都属于同一个 NSPersistentCloudKitContainer
。
在某些时候,我将对象的 backgroundContext
属性从 2 更新为 1,并将其 status
属性从 updatedAt
更新为 nil
后,将其保存在 Date()
中。
后来想取回这个更新后的对象,我的理解是取回总是返回持久化存储的内容。
因此,无论提取到哪个上下文,提取的对象都应该是相同的。然而,事实并非如此。
我还将 -com.apple.CoreData.ConcurrencyDebug 1
设置为启动参数,因此这不是 CoreData 多线程错误。
这是我的测试代码:
对象保存在这里:
let context = backgroundContext!
context.performAndWait {
assert(ItemStatus(rawValue: item.status) == .isBought)
item.status = ItemStatus.isToBuy.rawValue
item.updatedAt = Date()
_ = saveContext(context)
}
与
func saveContext(_ context: NSManagedobjectContext) -> Error? {
if !context.hasChanges { return nil }
let inserts = context.insertedobjects; if !inserts.isEmpty { print("Will save inserted objects: \(inserts)") }
let updates = context.updatedobjects; if !updates.isEmpty { print("Will save updated objects: \(updates)") }
let deletes = context.deletedobjects; if !deletes.isEmpty { print("Will save deleted objects: \(deletes)") }
do {
try context.save()
print("\(context.name!) saved")
} catch {
fatalError("Unresolved error")
}
return nil
}
let mwFetchRequest = NSFetchRequest<Item>(entityName: Item.entityName)
let passwordPredicate = nspredicate(format: "\(Schema.Item.password) == %@",password)
let namePredicate = nspredicate(format: "\(Schema.Item.name) == %@","mineral water")
let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [passwordPredicate,namePredicate])
mwFetchRequest.predicate = compoundPredicate
mwFetchRequest.returnsObjectsAsFaults = false
backgroundContext.performAndWait {
let bcItem = try! backgroundContext.fetch(mwFetchRequest)
print("backgroundContext: \(bcItem)")
}
viewContext.performAndWait {
let vcItem = try! viewContext.fetch(mwFetchRequest)
print(„viewContext: \(vcItem)")
}
Will save updated objects: [<ShopEasy.Item: 0x600000d7cf50> (entity: Item; id: 0x9698d776a7665623 <x-coredata://35BF43D6-4CF7-490D-B944-9DDFF2823AA1/Item/p1617>; data: {
buyPlaces = "<relationship fault: 0x600002e296a0 'buyPlaces'>";
fixedAtTopAt = nil;
howOftenBought = 1;
lastBoughtDate = "2021-01-24 13:02:09 +0000";
name = "mineral water";
password = "PW_1";
status = 1;
updatedAt = "2021-01-24 13:32:14 +0000";
})]
backgroundContext saved
…
backgroundContext: [<ShopEasy.Item: 0x600000d7cf50> (entity: Item; id: 0x9698d776a7665623 <x-coredata://35BF43D6-4CF7-490D-B944-9DDFF2823AA1/Item/p1617>; data: {
buyPlaces = "<relationship fault: 0x600002e296a0 'buyPlaces'>";
fixedAtTopAt = nil;
howOftenBought = 1;
lastBoughtDate = "2021-01-24 13:02:09 +0000";
name = "mineral water";
password = "PW_1";
status = 1;
updatedAt = "2021-01-24 13:32:14 +0000";
})]
viewContext: [<ShopEasy.Item: 0x600000d75ae0> (entity: Item; id: 0x9698d776a7665623 <x-coredata://35BF43D6-4CF7-490D-B944-9DDFF2823AA1/Item/p1617>; data: {
buyPlaces = (
"0x9698d776b10e5621 <x-coredata://35BF43D6-4CF7-490D-B944-9DDFF2823AA1/Place/p971>"
);
fixedAtTopAt = nil;
howOftenBought = 1;
lastBoughtDate = "2021-01-24 13:02:09 +0000";
name = "mineral water";
password = "PW_1";
status = 2;
updatedAt = nil;
})]
显然,对象首先使用 backgroundContext
正确保存,因此应该在持久存储中。
然后将其正确提取回 backgroundContext
。
但是在将同一个对象提取到 viewContext
中后,两个更改的属性 status 和 updatedAt 具有保存之前的值。
解决方法
后来想取回这个更新后的对象,我的理解 是 fetch 总是返回持久存储的内容。
获取选择基于持久存储的内容返回的对象,但默认情况下它不会更新基于对象的内存副本商店的内容。有 an option 可以做到这一点,根据我的经验,这是行不通的。要从商店更新现有对象,您可以刷新它或在您的上下文中设置合并,以便自动传播对商店的更改。