15.5. Deleting Data from Core Data

Problem

You want to delete a managed object (a row in a table) from a managed object context (your database).

Solution

Use the deleteObject: instance method of NSManagedObjectContext:

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

  [self createNewPersonWithFirstName:@"Anthony"
                            lastName:@"Robbins"
                                 age:51];

  [self createNewPersonWithFirstName:@"Richard"
                            lastName:@"Branson"
                                 age:61];

  /* Create the fetch request first */
  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

  /* Here is the entity whose contents we want to read */
  NSEntityDescription *entity =
  [NSEntityDescription entityForName:@"Person"
              inManagedObjectContext:self.managedObjectContext];
  NSSortDescriptor *ageSort =
  [[NSSortDescriptor alloc] initWithKey:@"age"
              ascending:YES];
  /* Tell the request that we want to read the
    contents of the Person entity */
  [fetchRequest setEntity:entity];

  NSError *requestError = nil;

  /* And execute the fetch request on the context */
  NSArray *persons =
  [self.managedObjectContext executeFetchRequest:fetchRequest
                                           error:&requestError];

  /* Make sure we get the array */
  if ([persons count] > 0){

    /* Delete the last person in the array */
    Person *lastPerson = [persons lastObject];

    [self.managedObjectContext deleteObject:lastPerson];

    NSError *savingError = nil;
    if ([self.managedObjectContext save:&savingError]){
      NSLog(@"Successfully deleted the last person in the array.");
    } else {
      NSLog(@"Failed to ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.