Delete all records in NSManagedObjectContext

Michael picture Michael · Nov 12, 2009 · Viewed 18.9k times · Source

Is there a way to delete all the records from an NSManagedObjectContext?

I'm using the following code to insert data:

NSManagedObjectContext * context = [[NSApp delegate] managedObjectContext];
NSManagedObject        * basket  = nil;

basket = [NSEntityDescription insertNewObjectForEntityForName:@"ShoppingBasket"
                                       inManagedObjectContext: context];  
[basket setValue:[firstSelectedObject valueForKey:@"accessoryID"]
          forKey: @"accessoryID"];

How do I delete all the records? I want something that's like the "remove:" function, but to remove everything.

Answer

Joshua Nozzi picture Joshua Nozzi · Nov 13, 2009

To delete all instances of a given entity (we'll use your ShoppingBasket), you can simply fetch all baskets then delete them. It's just a few lines of code:

NSManagedObjectContext * context = [self managedObjectContext];
NSFetchRequest * fetch = [[[NSFetchRequest alloc] init] autorelease];
[fetch setEntity:[NSEntityDescription entityForName:@"ShoppingBasket" inManagedObjectContext:context]];
NSArray * result = [context executeFetchRequest:fetch error:nil];
for (id basket in result)
    [context deleteObject:basket];

The alternative in a non-document-based app is to shut down your connection to the data store, delete the actual file, then reconnect (the template code that comes with a standard Core Data project will automatically create the file if it's absent). You then have a brand new, empty store.

Note, the code example ignores any possible error. Don't do that. :-)