Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Wednesday, December 18, 2013

iOS How to Purge a Set of Core Data Entities

So, you want to remove all of one type of Core Data entity from your datastore/database, eh?

Sometimes you just want to clear out all your data, whether because the user is explicitly asking for it to be deleted, or as part of a simple wiping process during a server fetch (fetching to store locally) when you're dealing with small amounts of data. If you find yourself needed to delete all of your entities from a table in Core Data, it may surprise you how you have to go about it.

Here's an example:


+(void)deleteAllEventsInManagedObjectContext:(NSManagedObjectContext *)context
{
  // Create a NSFetchRequest to fetch Event entity objects
  NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Event"];
  
  // Apply no filters, fetch them all
  request.predicate = [NSPredicate predicateWithFormat:@"1==1"];
  request.sortDescriptors = [NSArray arrayWithObject:nil];
  
  NSError *error = nil;
  NSArray *records = [context executeFetchRequest:request error:&error];
  
  // Write any errors to the console
  if(error){
    NSLog(@"%@", error);
  }
  
  // Iterate over the results, and delete them
  for(NSManagedObject *record in records)
  {
    // Delete by way of the NSManagedObjectContext it belongs to
    [context deleteObject:record];
  }
}

What surprised me the most was that it was necessary to fetch all the entities and then iterate over them deleting one by one. As far as I know, there continues to be no mass-destroy method in the SDK. On the plus side, this means you're forced to handle errors on a per-delete-basis that may arise from entity relationships-gone-bad, and I imagine that this is a good thing when your data model is more complex.

If you know of a better way, please leave it in the comments. And as always, please give us a +1 if you found this helpful to you.





About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates: http://www.blindnsdate.com

Popular Posts

Designed By Seo Blogger Templates