Delete all records in NSManagedObjectContext
Asked Answered
M

2

15

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.

Mixtec answered 12/11, 2009 at 21:21 Comment(0)
S
39

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. :-)

Spine answered 13/11, 2009 at 16:10 Comment(4)
There isn't a 1 code line solution ? i.e. Flush Context, or empty context, or deleteAllContact
Nope. No convenient "DROP DATABASE;" stand-in.Spine
Yes there is, see my reply below. Deletes the database and let's you re-create it.Sniffy
Please read my actual post. I specifically stated you could do the same thing you're mentioning in your answer, but this does not work for document based apps on OS X. Since the OP said cocoa and not Cocoa Touch or iOS, my answer was appropriate.Spine
S
4

A much quicker way would be to just remove store entirely. This way you're not wasting any time fetching objects, or enumerating through them as the other answer does.

NSError *error;
NSURL *applicationDocumentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *storeURL = [applicationDocumentsDirectory URLByAppendingPathComponent:@"MyCDStore.sqlite"];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];

Don't forget to re-create it after you have deleted it.

Sniffy answered 30/9, 2011 at 20:59 Comment(6)
Is this method safe to use ? Can we assume that the core data will always be saved with this name, this location always?Chadchadabe
Yes, if you're using the same managed object context to re-create it.Sniffy
This assumes iOS and neglects problems with OS X document-based data stores. You can't just whack a user's document like this.Spine
Joshua Nozzi couldn't explain it better why your response is not goodSincerity
How would I go about re-creating it?Keli
I really recommend checking out MagicalRecord. Creating/re-creating is as easy as [MagicalRecord setupAutoMigratingCoreDataStack]; :)Sniffy

© 2022 - 2024 — McMap. All rights reserved.