I need some advice how to go about this:
1) I retrieve an XML from a web server.
2) I want to store all the entities (i.e. Friends) from that XML locally on the device, using Core Data.
3) So I parse the XML and make an Managed Object for every Friend in that XML
4) But I want to make sure that I don’t add one Friend multiple times into the DB. How could I achieve that?
————– my strategy thoughts on this —————-
A) While parsing the XML, I create an Managed Object of the Friend entity as soon as there is a Friend element started. At that point I don’t know which friend it will be, until the NSXMLParser stepped through all the upcoming attributes like firstName, id, etc.; After the End-tag for the Friend element, I have that friend in my Managed Object Context. Then I make an NSFetchRequest to see if that friend is stored already. Problem is, that the new friend is already part of the context, so probably Core Data will return always a match!?
B) I need two different Managed Object Contexts so that the parsed Friends first go into MOC_A, and then I query MOC_B (the actual local store) without that the new parsed friends disturbe my query to the local store. So I can find out if the friend already existed.
C) While parsing a friend from the XML I just create a new Managed Object instance WITHOUT adding it to an Managed Object Context (possible ?!). Later, when the friend is pares completely, I check against Core Data if it is stored. If not, I add it. Otherwise I throw the object away.
D) I need another strategy.
You should use a new indexed attribute in your Core Data entity to store the unique ID from the XML. Before adding an object, you will have to manually check if an object with that ID already exists.
UPDATE
The key is to not add a managed object to the context until you have determined that it is new.
This is pretty straightforward given the unique ID, but it sounds like you can’t parse for the unique ID first. In that case you should use a temporary mutable dictionary (NSMutableDictionary) to store the data as it’s parsed.
If you determine that the friend is new, you can create it and copy the data over from the dictionary. If the friend is not new, you can discard the dictionary.