I notice weird issues where NSFetchedResultsController
returns in its fetchedObjects
two instances of the same object.
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
items = (controller.fetchedObjects ?? []) as! [Item]
print(items)
// Prints:
// - 0 : <Item: 0x600000d40e10> (entity: Item; id: 0x600002e6b2e0 <x-coredata:///Item/tE1646DB0-C3C2-4AE1-BC32-6B10934F292C2>; ....
// - 1 : <Item: 0x600000d40e10> (entity: Item; id: 0x600002e6b2e0 <x-coredata:///Item/tE1646DB0-C3C2-4AE1-BC32-6B10934F292C2>; ...
print(items[0] == items[1]) // true !!!
}
The issue occurs after adding a new item and saving both contexts.
func weirdTest() {
print("1. Adding.")
let item = Item(context: viewContext)
item.id = UUID()
viewContext.processPendingChanges()
print("2. Saving.")
viewContext.performAndWait {
try! viewContext.save()
}
rootCtx.performAndWait {
try! rootCtx.save()
}
}
Here's my Core Data Stack:
View Context (main thread) --> Background Context --> Persistent Store Coordinator
Ahd here's how I configure my contexts:
lazy var rootCtx: NSManagedObjectContext = {
let rootCtx = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
rootCtx.persistentStoreCoordinator = coordinator
rootCtx.automaticallyMergesChangesFromParent = true
return rootCtx
}()
lazy var viewContext: NSManagedObjectContext = {
let ctx = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
ctx.parent = rootCtx
ctx.automaticallyMergesChangesFromParent = true
return ctx
}()
Anyone has any idea what's going on here? :<