1

I'm trying to find the best way to insert large amounts or records using Core Data.

I have tried two approaches and I am wondering if there's a better way. Here are the two scenarios I have tried:

Preconditions

The structure of the data to be inserted is the following:

  • Entities: Package, Product
  • Relationships:
    • A package can contain one or more products
    • A product can be in only one package

The data to be imported is in formatted as JSON and it's in plain text files. I have one file with the list of all Packages (i.e., a list of ids, names) and one file with the list of Products per Package (i.e., a list of package id, product id, product name)

Scenario 1

Load the Packages' JSON into an NSArray
Load the Products' JSON into an NSArray
For each Package in Packages array 
  Create Package entity
  Filter Products array using Package Id using NSPredicate
  Create Product entity and associate with current Package
  Save Managed Object Context

Scenario 2

Load the Packages' JSON into an NSArray
Load the Products' JSON into an NSArray
// insert all Packages first
For each Package in Packages array 
  Create Package entity
  Save Managed Object Context

// insert and associate all Products
For each Product in Products array
  Fetch Packages with package id == current Product's package id
  Create Product entity and associate it with the fetched Package
  Save Managed Object Context

I would like to know of any better strategy to load large amounts of data to my storage.

I'm not really happy with any of the two methods since both of them are synchronous inserts and lock my app, I'm currently reading how to make asynchronous inserts but I haven't quite get it yet.

4

1 回答 1

2

首先,并发:在子上下文中插入并调用

[managedObjectContext performBlock:]

您可以通过 NSNotification 或通过获取的结果控制器委托方法通知 UI 更改。

第二,导入策略:我认为你的两种方法都很好。这实际上取决于哪种方法更快的数据。但是,请注意以下优化:

  1. 分批保存。跟踪实体计数并在批次已满时保存。尝试直到找到最快的解决方案。从几百个实体开始(例如 500),但理想的数字可能是 2000。不要在循环中的每次迭代时保存上下文。

  2. 在子上下文中,关闭撤消管理器。阅读核心数据编程指南“高效导入数据”中的相关内容。(编辑:Apple 已删除此信息。)

于 2013-09-06T07:38:18.467 回答