newBackgroundContext苹果在其官方地震示例中向我们展示了如何使用后台线程(通过使用)执行繁重的写入操作- https://github.com/yccheok/earthquakes-WWDC20
但是,对于大量的读操作呢?(数百万行用于压力测试目的)
当我们第一次启动应用程序并且应用程序正在从 CoreData 读取大量数据时,我们还希望我们的应用程序 UI 具有响应能力。
以下是使用的代码片段NSFetchedResultController。
let controller = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: persistentContainer.viewContext,
sectionNameKeyPath: nil, cacheName: nil)
controller.delegate = fetchedResultsControllerDelegate
// Perform the fetch.
do {
// This statement tooks some time to complete if you have a lot of rows.
try controller.performFetch()
} catch {
fatalError("Unresolved error \(error)")
}
Run Code Online (Sandbox Code Playgroud)
我们尝试controller.performFetch()使用后台线程来执行。尽管如此,但不知道为什么,用户界面仍然没有响应能力。我的猜测是,在NSFetchedResultsController占用UI主线程之后,要执行一些耗时的I/O读操作。
let controller = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: persistentContainer.viewContext,
sectionNameKeyPath: nil, cacheName: nil)
controller.delegate = …Run Code Online (Sandbox Code Playgroud)