Post not yet marked as solved
Post marked as unsolved with 7 replies, 1,390 views
On iOS 14 beta 5 and 6, when fetching a request on a new private queue context that has persistentContainer.newBackgroundContext() as a parent, returns the wrong number of objects (always 0 even if there are objects in the db).
The same code on iOS 13 and iOS 14 beta 1 to 4 returns the correct number of objects.
Am I doing something wrong?
In the following sample code the second assert fails on Xcode 12 beta 5 and 6.
let rootContext = self.persistentContainer.newBackgroundContext()
let viewContext = persistentContainer.viewContext
let goodRequest = NSFetchRequest<NSFetchRequestResult>()
goodRequest.entity = NSEntityDescription.entity(forEntityName: Podcast.entityName(), in: viewContext)
let batchRequest = NSFetchRequest<NSFetchRequestResult>()
batchRequest.fetchBatchSize = 20
batchRequest.entity = NSEntityDescription.entity(forEntityName: Podcast.entityName(), in: viewContext)
let entityDescription = NSEntityDescription.entity(forEntityName: Podcast.entityName(), in: viewContext)!
let newPodcast = NSManagedObject(entity: entityDescription, insertInto: viewContext) as! Podcast
newPodcast.title = "The Title"
if viewContext.hasChanges {
		try? viewContext.save()
}
		
guard
		let goodPodcastsAfter = try! viewContext.fetch(goodRequest) as? [Podcast],
		let batchPodcastsAfter = try! viewContext.fetch(goodRequest) as? [Podcast]
else {return}
NSLog("After adding new podcast - podcast count - good request: \(goodPodcastsAfter.count) - batch request: \(batchPodcastsAfter.count)")
assert(goodPodcastsAfter.count == batchPodcastsAfter.count, "Count of fetched podcasts should match")
let newContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
newContext.parent = rootContext
newContext.automaticallyMergesChangesFromParent = true
newContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
newContext.perform {
		guard
				let goodPodcastsInNewContext = try? newContext.fetch(goodRequest) as? [Podcast],
				let batchPodcastsInNewContext = try? newContext.fetch(batchRequest) as? [Podcast]
		else {return}
		
		NSLog("In new context - podcast count - good request: \(goodPodcastsInNewContext.count) - batch request: \(batchPodcastsInNewContext.count)")
		assert(goodPodcastsInNewContext.count == batchPodcastsInNewContext.count, "Count of fetched podcasts should match")
}