CoreData 如何实现批量插入 (教程含源码)
几乎所有项目都需要将批量数据一次性添加到数据库中。在我的例子中,它主要是在安装到新设备时下载用户数据。
我见过包括我在内的一些新开发人员使用for-loop从数组中一个一个地获取对象,然后将其添加到上下文中。
好的,让我们来看看代码。
例子:
/// 创建批量插入请求Create Batch Insert Request
let insertRequest = NSBatchInsertRequest(entity: BookKeeper.entity(), objects: booksArray)
/// 设置结果类型,在我们的例子中我们需要对象 IDSet the Result Type, in our case we need object IDs
insertRequest.resultType = NSBatchInsertRequestResultType.objectIDs
/// 执行使用已创建的后台上下文的请求。Execute the request using the background context already created.
let result = try? bgContext().execute(insertRequest) as? NSBatchInsertResult
/// 最后,我们使用从结果中获得的 objectID 进行合并。Finally we merge using the objectIDs we got from the results.
if let objectIDs = result?.resul