Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all records in NSManagedObjectContext

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.

like image 666
Michael Avatar asked Nov 12 '09 21:11

Michael


People also ask

How do I delete all entries in Core Data?

Delete Everything (Delete All Objects, Reset Core Data) One approach to delete everything and reset Core Data is to destroy the persistent store. Deleting and re-creating the persistent store will delete all objects in Core Data.

What is delete rule in Core Data?

A delete rule defines what happens when the record that owns the relationship is deleted. A delete rule defines what happens when the record that owns the relationship is deleted. Select the notes relationship of the Category entity and open the Data Model Inspector on the right.

Is NSManagedObjectContext thread safe?

The NSManagedObjectContext class isn't thread safe. Plain and simple. You should never share managed object contexts between threads. This is a hard rule you shouldn't break.

What is NSManagedObjectContext in Swift?

An object space to manipulate and track changes to managed objects.


1 Answers

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

like image 114
Joshua Nozzi Avatar answered Oct 08 '22 23:10

Joshua Nozzi