Swift Import Big Data JSON and Master Data
What would be the best approach for making a large JSON data request and storing it in Core Data?
I am currently receiving a JSON file from the server that contains a list of jobs with related entities, then I parse it and populate a Core Data Entity which works fine.
When the user refreshes their list, I will be making a new request to the server, so I guess I will need to completely delete all existing entities and repopulate the DB.
How is such an operation achieved in Swift?
I found several tutorials and examples using Dataseeding that seem close enough.
If you need examples or existing code please let me know
source to share
This question has been asked and answered many times on stack overflow. You want to import data and then update to solve the classic insert / update problem.
You want to do this import on a background thread to avoid interrupting your UI.
You don't want to delete all objects. You want to use KVC to get all ids from incoming JSON, then do one fetch from CD to see what already exists.
Then you want to iterate over the JSON, inserting if it doesn't already exist, and doesn't update when it does.
Since your UI has to use NSFetchedResultsController
, you will just need to keep it private NSManagedObjectContext
and your UI will update as a result.
source to share
Uniqueness was introduced for Core Data in iOS9. Therefore, you don't need to use NSFetchedResultsController
and compare / clear old data.
You just need to do this:
managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
You can find a more detailed answer here - How to add unique constraints for some fields in master data
source to share