Example: I have a list of friends which I retrieve as XML from a web server. On the device I want to store those friends with an update feature locally. But I only want to store NEW friends. To keep it simple I distinguish them by their first name only (yes thats bad!).
As the XML parser walks through the XML, it generates managed objects for all the friends and hangs them into the managed object context. But before I save the context, I want to get rid of all those "new" friends which are already in the database. Currently I have:
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Friend" inManagedObjectContext:context];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
[request setPredicate:[NSPredicate predicateWithFormat:@"firstName == 'George'"]];
NSError *error = nil;
NSArray *array = [context executeFetchRequest:request error:&error];
The problem is, probably: It will find the friends in the whole managed object context, so also those which are NOT in the database yet. How could I make sure that I only save those which are really new开发者_运维技巧, and throw the duplicates away before saving?
Use a unique ID. Add an attribute to your Friend entity for it. For example, it could be the primary key from the web database.
精彩评论