Cliffordwh
Cliffordwh

Reputation: 1430

UITableView handling Json and Core Data

What would be the best practise and best for user experience to achieve the following?

1:) Retrieve data from JSON
2:) Store in Core Data
3:) Display in UITableViewController

Do i store the JSON first, then populate the table using the stored data?
OR
Do i store it in the Core Data (background process) and populate the table using the JSON for the first time?

I want the user to be presented with a UITableview with minimum load time. Thanks

Upvotes: 0

Views: 397

Answers (3)

Ian
Ian

Reputation: 12768

The course of action in this matter heavily depends on: A. The amount of JSON data you are downloading B. How effective your backend is at only sending necessary JSON results (rather than sending everything in bulk) C. How you are attaching Core Data to your UITableViewController.

I recently made a pretty big project that does exactly this, which involved fetching a pretty big chunk of JSON, parsing it, and inserting it into Core Data. The only time there is any delay is during the initial load. This is how I accomplished it:

  1. Download JSON. Cast as [[String: AnyObject]]: if let result = rawJSON as? [[String: AnyObject]] {}
  2. Check to see if IDs for objects already exist in Core Data. If that object already exists, check if it needs update. If it doesn't exist, create it. Also check if IDs have been deleted from the JSON, if so remove them from.
  3. Use NSFetchedResultsController to manage data from Core Data and populate the UITableView. I use NSFetchedResultsController rather than managedObjectContext.executeFetchRequest() because NSFetchedResultsController has delegate methods that are called every time the managedObjectContext is updated.

Upvotes: 0

KrisJones
KrisJones

Reputation: 188

This is what I would do:

  1. Create your Core Data database and model.
  2. Create a data access layer that will contain the read and write methods for each of your objects
  3. In the read functions you can query the core data, if there is data then return that. Then in the background call the web server and and update your core data with the new JSON.
  4. If there is no data go and request it from the web server, populate your core data tables using the JSON and then return the data from the core data so it is always consistent.

You can also have a last update date on your data so you are only requesting the new data from the web server that isnt already in your local core data DB. This will reduce the amount of data coming down to your ios device.

Upvotes: 1

donnywals
donnywals

Reputation: 7591

If you want minimum load time then I'd serve from JSON and that save to CoreData afterwards. That way the user can see content straight away without first having to wait for all the data to be saved (and parsed).

Upvotes: 0

Related Questions