O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

18.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]
                                    initWithEntityName:@"Person"];

    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 delete the last person in the array.");
        }

    } else {
        NSLog(@"Could not find any Person entities in the context.");
    }

    self.window = [[UIWindow alloc] initWithFrame:
                   [[UIScreen mainScreen] bounds]];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

Note

In this example code, we are using the createNewPersonWithFirstName:lastName:age: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required