提问者:小点点

CoreData-backgroundContext的使用


我试图理解CoreData中的backgroundContext的概念。虽然我读了几篇关于它的文章,但我仍然不确定它的目的。

我有一个应用程序使用核心数据,允许用户创建,更新或删除记录。用户还可以获取他添加的数据。我想确保如果有很多记录,在获取数据时不会影响UI的流。

所以我研究了一些背景上下文。我根据自己理解的内容执行了以下操作。但我不确定这是否是一个正确的解决办法。我的想法是--如果我进入背景,它不能影响主线。

//I have an PersistentContainer created by Xcode.

//I create an backgroundContext.
self.backContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.newBackgroundContext()

//Then if the user adds a new record, it's added to backContext and saved to mainContext
...
let newRecord = Record(context: self.backContext!)
...
self.backContext!.save()
self.context!.save() // mainContext
...

//If the user fetches the data I use:
self.backContext.perform {
...
}

//Since I want to show results in UI, I know these objects (from fetch) exist just in the background thread, so instead I fetch for IDs 
.resultType = .managedObjectIDResultType

//Now I have IDs of fetched objects, so I restore objects in main thread using their IDs:
let object = try? self.backContext.existingObject(with: ID) as? Record

//and I can finally use fetched objects to update UI.

问题是:

  • 我现在做的事情对吗?(它工作得很好)
  • 这会解决用户获取大量数据时冻结UI的问题吗?

我们如何正确使用backgroundContexts?为什么不建议直接使用MainContext?如何防止在取大数据的同时冻结UI?

还有一个问题:如果我使用FetchedResultsConteroller-我需要处理冻结UI的问题吗?(在等待第一个(init)提取结果时?)

当然,我忽略了在获取数据时,我的上下文被阻塞,因此我无法创建新记录


共1个答案

匿名用户

如果您正在获取要显示在屏幕上的对象,那么您绝对应该针对主线程上下文使用fetch请求。核心数据是为这个特定的用例而设计的,您不应该因为执行取数而经历速度减慢或冻结。如果你遇到了问题,那么在instruments中分析你的应用程序,找出实际的减速在哪里。

如果您正在执行大量或长时间运行的工作,例如处理大型API响应,您已经证明这会影响主线程的性能,则需要使用背景上下文。