Clear all objects from an entity


/ Published in: Objective C
Save to your folder(s)

How do you delete all objects in an entity in Core Data? It's not as simple or straightforward as it is in SQL/SQLite. here's one reasonably quick way...

taken from stackoverflow


Copy this code and paste it in your HTML
  1. - (BOOL)clearEntity:(NSString *)entity
  2. NSManagedObjectContext *myContext = [(<#YourAppDelegate#> *)[[NSApplication sharedApplication] delegate] managedObjecContext];
  3. NSFetchRequest *fetchLLObjects = [[NSFetchRequest alloc] init];
  4. [fetchAllObjects setEntity:[NSEntityDescription entityForName:entity inManagedObjectContext:myContext]];
  5. [fetchAllObjects setIncludesPropertyValues:NO]; //only fetch the managedObjectID
  6.  
  7. NSError *error = nil;
  8. NSArray *allObjects = [myContext executeFetchRequest:fetchAllObjects error:&error];
  9. // uncomment next line if you're NOT using ARC
  10. // [allObjects release];
  11. if (error) {
  12. [[NSApplication sharedApplication] presentError:error];
  13. }
  14.  
  15. for (NSManagedObject *object in allObjects) {
  16. [myContext deleteObject:object];
  17. }
  18.  
  19. NSError *saveError = nil;
  20. if (![myContext save:&saveError]) {
  21. [[NSApplication sharedApplication] presentError:error];
  22. }
  23.  
  24. return (saveError == nil);
  25. }

URL: http://stackoverflow.com/a/1383645/215494

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.