O'Reilly logo

iOS 5 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

13.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]; /* 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 delete the last person in the array."); } } else { NSLog(@"Could not find any Person entities ...

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