views:

131

answers:

3

Hi guys,

I have an application that loads core data, then calls the XML Web Service to get updated data. I basically want my app, rather than to erase all the data and load everything (including new) to persist, I want it to add only the new stuff onto the existing stack (without duplication).

What's the general consensus strategy for something like this?

+1  A: 

If each item in your xml data set has a unique key, you can just use that key to find the existing record and update it with the new info

Corey Floyd
+1  A: 

I fetch an NSSet* of all persisted objects and then perform an intersection operation on that set of NSManagedObject instances with a new managed object, which is populated with the data from an individual XML element and its contents.

If there is something left from that intersection, that means I have that element already in my data store. So I update the existing, already-persisted managed object's properties with data from the XML element and save, discarding the new managed object.

If I have an empty set, the newly created managed object gets saved into the data store directly.

I don't have a hash value available to compare between the persisted data and the XML data, so this works reasonably well.

Alex Reynolds
Intersection? sorry mate, not sure i quite follow
Doron Katz
When you perform a fetch from your Core Data store, you can retrieve an `NSSet*` of managed objects of whatever entity type (e.g. "Book", "Recipe"). The `NSSet` and `NSMutableSet` classes contain several methods for basic set operations, such as intersection, union, etc. You can use these to determine if two sets have elements (e.g. managed objects) in common, which will help your application decide whether it needs to update an existing object or add a new one. In other words, if you think of your Core Data as one circle, and your XML as another circle, draw a Venn diagram between them.
Alex Reynolds
A: 

Like Corey says, find a unique key to use in your data. Search the original data for that key and if it's not found, the object is a new one and can be inserted. If the object is already in the original data, discard it.

If there's a chance that the data will be updated over time (objects getting updated on the web side) then you'll have to compare the old (iphone) object and the new object with the same key. If they're the exact same, discard the new one. If not, replace the old one.

If there's no unique key you can use, you're going to have to do this comparison on all objects. I'm not sure of the quickest way to compare two managed objects, but you could try creating a managed object with the new (web) data and comparing it with each of the objects in the original.

nevan