11

I'm trying to sync my data from a web service in a simple way. I download my data using AFNetworking, and using a unique identifier on each object, I want to either insert, delete or update that data.

The problem is that with Core Data you have to actually insert objects in the NSObjectManagedContext to instantiate NSManagedObjects. Like this:

MyModel *model = (MyModel *)[NSEntityDescription insertNewObjectForEntityForName:@"MyModel" inManagedObjectContext:moc];
model.value = [jsonDict objectForKey:@"value"];

So when I get the data from the web service, I insert them right away in Core Data. So there's no real syncing going on: I just delete everything beforehand and then insert what's being returned from my web service.

I guess there's a better way of doing this, but I don't know how. Any help?

3
  • 1
    I've answered a similar question here: stackoverflow.com/questions/5035132/… Hope it helps.
    – chris
    Jan 17, 2014 at 21:16
  • Normally I'd expect to try and look up existing objects before creating new ones, so that I could update rather than replace. Jan 17, 2014 at 22:09
  • There is no easy answer to your question. Syncing data from a remote server with a mobile device, which is possibly offline for a long duration, is actually a "hard problem". I dare to state that all "easy" solutions, suggestions and answers you can find in the web (and also on SO) won't work in real scenarios and all do have a number of obvious and also more subtle problems. You should also be very careful when looking for a third party service which offers a "syncing" solution. Oftentimes, this only includes a very basic feature set. But perhaps, this is already sufficient for your app. Jan 22, 2014 at 10:26

2 Answers 2

12
+200

You are running into the classic insert/update/delete paradigm.

The answer is, it depends. If you get a chunk of json data then you can use KVC to extract the unique ids from that chunk and do a fetch against your context to find out what exists already. From there it is a simple loop over the chunk of data, inserting and updating as appropriate.

If you do not get the data in a nice chunk like that then you will probably need to do a fetch for each record to determine if it is an insert or update. That is far more expensive and should be avoided. Batch fetching before hand is recommended.

Deleting is just about as expensive as fetching/updating since you need to fetch the objects to delete them anyway so you might as well handle updating properly instead.

Update

Yes there is an efficient way of building the dictionary out of the Core Data objects. Once you get your array of existing objects back from Core Data, you can turn it into a dictionary with:

NSArray *array = ...; //Results from Core Data fetch
NSDictionary *objectMap = [NSDictionary dictionaryWithObjects:array forKeys:[array valueForKey:@"identifier"]];

This assumes that you have an attribute called identifier in your Core Data entity. Change the name as appropriate.

With that one line of code you now have all of your existing objects in a NSDictionary that you can then look up against as you walk the JSON.

3
  • I pretty much do a batch request to my webservice, and every object in the JSON array response has a unique id. So I guess I could do the loop as you said. However, is there an efficient way to do it? The best way I can see is to loop over the Core Data results and build a map with the unique ids as indices, and then loop over the JSON chunk and insert/delete/update as necessary. See any better way? Jan 20, 2014 at 3:03
  • @omegatai If you think about it, this above approach doesn't answer when to insert, when to delete and when to update, which object, and that cannot be done without providing a sync algorithm, which in turn requires meta-information managed local and remote. So, this approach would only work if your local data is read only and does not allow delete or inserts. And if this is the case, a simple approach is juts empty your local db and insert all objects received from the server. If you have less than 1000 objects this is quite fast as well. Jan 22, 2014 at 19:10
  • 2
    If the web-service returns all objects and not just the updated objects you could also set a delete flag on all your objects, do your inserts and updates like described above and when you are done you delete all flagged objects. this way your data can be read and write.
    – nanako
    Mar 20, 2014 at 8:50
0

The easiest thing to do is to restore the Json to a entity that maps properly to it. Once you've mapped it, determine if a object matching the entities ID exists already, if so then fetch the entity and merge changes. If not, create a new entity in Core Data and restore the Json to it.

I'm building a app were I do client side syncing with Evernote. They keep a syncUpdate number on all of their objects and at the server level. So when I start my sync I check if my clients syncUpdate count is less than the servers. If so, I know I am out of sync. If my updateCount is at 400 and the server is at 410, I tell the server to provide me with all objects between updateCount 400 and 410. Then I check if I already have the objects or not and perform my update/create.

Every time a object is modified on the server, that objects updateCount is increments along with the servers.

The server also keeps a time stamp of the last update, which I can check against also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.