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.