cannyboy cannyboy - 1 month ago 9
iOS Question

How to search thru Core Data entities and delete certain objects

I'm unclear how to remove certain objects from Core Data database. I think I've got it working so I can find the objects, but don't know how to delete them from Core Data. In this example I'm searching the entity News for items which have expired. I use the 'expires' property (an int 32 unix time stamp) and see if the number is less than the current unix time stamp. Not sure if the NSPredicate is right in this.

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"News" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];

// Set up predicate here?
NSPredicate *pred = [NSPredicate predicateWithFormat:@"expires < %i", dateInt]; // dateInt is a unix time stamp for the current time
[request setPredicate:predicate];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"forename" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
NSError *error;
NSMutableArray *mutableFetchResults = [[[managedObjectContext executeFetchRequest:request error:&error] mutableCopy] autorelease];
[request release];

// delete the found objects here?

Answer

Call -[NSManagedObjectContext deleteObject:] for every object you want to delete, then commit the changes.