I have an application that uses CoreData and has several background contexts (NSManagedObjectContext).
While writing some tests I've observed a weird behavior that seems to be controversial with official documentation: Changes from one context are automatically propagated to another one, while .automaticallyMergesChangesFromParent is set to false in both contexts.
Both contexts are received from NSPersistentContainer - one is from .viewContext, other - with .newBackgroundContext() function.
as save says, on context saving changes are committed to context's parent store, which is NSPersistentContainer.
But in fact, changes also appear in another context, despite the fact automaticallyMergesChangesFromParent == false (it's a default value).
let persistentContainer = NSPersistentContainer(name: "TESTING")
let mainContext = persistentContainer.viewContext
let otherContext = persistentContainer.newBackgroundContext()
//test entity is created on anotherContext
let entity: TestEntity = NSEntityDescription.insertNewObject
(forEntityName: String(describing: TestEntity.self),
into: anotherContext) as! TestEntity
entity.statusCode = "Testing"
//prepare fetch request for test entity
let fetchReq: NSFetchRequest<TestEntity> = TestEntity.fetchRequest()
fetchReq.predicate = NSPredicate(format: "statusCode = %@",
argumentArray: ["Testing"])
//ensure that entity is not present in mainContext
let entityFromMain = try! mainContext.fetch(fetchReq)
XCTAssertEqual(entityFromMain.count, 0)
//save context that has entity
try! otherContext.save()
//ensure that changes from parent store aren't merged automatically
XCTAssertFalse(mainContext.automaticallyMergesChangesFromParent)
//get inserted entity from mainContext
let entityOnMainAfterSaving = try! mainContext.fetch(fetchReq)
//entity is present in mainContext
XCTAssertTrue(entityOnMainAfterSaving.count > 0)
Expected output - entityOnMainAfterSaving should not contain a newly created entity, but it is already there, although mainContext wasn't refreshed.
UPDATE:
I'm asking this because in my app there is a situation, where:
1. entity's property is changed in otherContext
2. otherContext is saved
3. entity is received through viewContext
4. property's value is not updated to its state as in p.1 (!)
At the same time, property's value will get updated if viewContext.refreshAllObjects() is called right before fetching in p.3