Question

In my app I store data from a JSON file in this way (it's a example for an identity)

NSManagedObjectContext *context = [self managedObjectContext];

for (id element in array){

    NSLog(@"element:%@", element);

Str *str = [NSEntityDescription insertNewObjectForEntityForName:@"Str" inManagedObjectContext:context];
Id_loc *loc = [NSEntityDescription insertNewObjectForEntityForName:@"Id_loc" inManagedObjectContext:context];
loc.id_loc = @"id_1";
[str addLocObject:loc];
}

The problem is that that I parse this JSON every day from a web service; so every day it can change data and number of its "Str" identity (an object of my JSON). The question is, what's the better solution to update my core data DB? I have two possibilities:

1- update my DB with NSFetchRequest, check if an element exist, and update it; if it not exist, I should create it. And finally if an object is not present in JSON but it's inside my core data DB, I should delete it, it's a complex series of controls.

2- delete all core data db and populate again with new JSON file.

In your opinion, what's the better choice?

I say you that in my app I must only read my db, and I don't need to delete or modify it when I use it.

Was it helpful?

Solution

For my app - where I use CoreData as well - I decided to go with option 1, for several reasons.

First on all it's just a bit more coding, but performance is so much better with that approach. If you are planning to use NSFetchedResultController you should definitely go with update option. Otherwise it will listen to your changes and it will reload all the views so many times, because you delete all objects and readd them.

Most important removing all objects is really expensive operation in CoreData because you have to fetch all objects first, than delete them one by one !!! It's really bad idea :) For several hundreds entries it's really taking application performance down if you are planning to do updates in background not blocking a screen during update process.

As an optimization I would recommend to keep on your server side timestamp for each object and pull only changes from last updated time on mobile side - incremental updates.

OTHER TIPS

Option 1 is generally better but obviously can be more costly depending on the changes and batch management. Option 2 is always costly, but it less error prone. Option 2 adds constraints related to saving additional information (maybe not a concern at the moment).

Ideally, you want to leverage an existing solution providing an implementation of option 1 which is tested and offers performance / memory efficiency options. Something like RestKit (which can use a temporary in-memory cache to find duplicates during the mapping process). As a side benefit, you can also simplify other mapping code you might have.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top