I have a small core data library. I use contexts this way:
public private(set) lazy var masterContext: ManagedObjectContext = { [weak self] in
let context = ManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
context.persistentStoreCoordinator = self?.persistentStoreCoordinator
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
return context
}()
public lazy var viewContext: ManagedObjectContext = { [weak self] in
let context = ManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
context.parent = self?.masterContext
return context
}()
public var newTemporaryContext: ManagedObjectContext {
let context = ManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
context.parent = viewContext
return context
}
I usually create a temporary context to insert new data, once it's done, I get that data using the viewContext
These are my tests:
override func setUp() {
super.setUp()
let bundle = Bundle(for: FilterTests.self)
kangaroo = KangarooStore(name: "TestDB", storageType: .memory, bundle: bundle)
kangaroo.loadStoreSync()
kangaroo.saveSync(in: .view, block: { context in
let entity2 = TestEntity(in: context)
entity2.id = 2
entity2.name = "entity2"
entity2.lastname = "test"
let entity1 = TestEntity(in: context)
entity1.id = 1
entity1.name = "entity1"
entity1.lastname = "test"
let entity5 = TestEntity(in: context)
entity5.id = 5
entity5.name = "entity5"
entity5.lastname = "test"
let entity6 = TestEntity(in: context)
entity6.id = 6
entity6.name = "entity6"
entity6.lastname = "test"
})
}
func testFilterInViewContext() {
do {
let predicate = NSPredicate(format: "id = %@", 1 as NSNumber)
let query = Query<TestEntity>(in: kangaroo.viewContext).filtered(using: predicate)
let entities = query.execute()
XCTAssertEqual(entities.count, 1)
XCTAssertEqual(entities[0].id, 1)
XCTAssertEqual(entities[0].name, "entity1")
}
}
on iOS 13.6 and backwards, "testFilterInViewContext" runs fine, but in iOS 14 beta 6 it fails.
What could be happening? Thanks in advance!