views:

2714

answers:

2

I'm using Core Data to locally persist results from a Web Services call. The web service returns the full object model for, let's say, "Cars" - could be about 2000 of them (and I can't make the Web Service return anything less than 1 or ALL cars.

The next time I open my application, I want to refresh the Core Data persisted copy by calling the Web Service for all Cars again, however to prevent duplicates I would need to purge all data in the local cache first.

Is there a quicker way to purge ALL instances of a specific entity in the managed object context (e.g. all entities of type "CAR"), or do I need to query them call, then iterate through the results to delete each, then save?

Ideally I could just say delete all where entity is Blah.

thanks, Adam

A: 

Why not fold in the data that you receive with the existing cache? Otherwise it's not really 'refreshing', it's 'starting again' and you might as well drop/delete the SQLLite file and start again (assuming you're not persisting other data as well).

AlBlue
+18  A: 

Fetch 'em all and delete 'em all:

NSFetchRequest * allCars = [[NSFetchRequest alloc] init];
[allCars setEntity:[NSEntityDescription entityForName:@"Car" inManagedObjectContext:myContext]];
[allCars setIncludesPropertyValues:NO]; //only fetch the managedObjectID

NSError * error = nil;
NSArray * cars = [myContext executeFetchRequest:allCars error:&error];
[allCars release];
//error handling goes here
for (NSManagedObject * car in cars) {
  [myContext deleteObject:car];
}
Dave DeLong
I would also configure the fetch to only retrieve the NSManagedObjectID to reduce any overhead from loading in the full object structure.
Marcus S. Zarra
@Marcus +1 excellent suggestion!
Dave DeLong
It's not obvious how to only fetch the NSMangagedObjectID.. use [allCars setIncludesPropertyValues:NO]; (and don't bother hunting around for how to make an NSPropertyDescription for the object ID!)
ohhorob
Garry
@Garry whoops, thanks for catching that! Edited the answer.
Dave DeLong
@Marcus please show the code for your suggestion. Thank you.
MattDiPasquale
Is there a faster way to do this with one command? Like in SQL you could do something like, DROP TABLE entity_name. But, I don't want to delete the whole SQL file because I only want to delete all objects of a specific entity, not other entities.
MattDiPasquale
@Matt no, because you're not dealing with a database. You're dealing with a graph of objects, and if you want to destroy all the objects, you have to destroy them all individually.
Dave DeLong
@Matt it would be easiest if Dave updated his answer with that addition. Code does not show up well in comments.
Marcus S. Zarra
@Matt @Marcus edited answer.
Dave DeLong
@Marcus @Dave Thanks!
MattDiPasquale