The API for handling bulk deletes was added to Core Data after bulk updates. Therefore, the API is very similar.
| - (void)deleteOldRecipes |
| { |
| NSManagedObjectContext *moc = [self writerContext]; |
| [moc performBlock:^{ |
| NSDate *yearOld = [self dateFrom1YearAgo]; |
| NSBatchDeleteRequest *request = nil; |
| NSFetchRequest *fetch = nil; |
| NSBatchDeleteResult *result = nil; |
| NSPredicate *predicate = nil; |
| NSError *error = nil; |
| |
| fetch = [NSFetchRequest fetchRequestWithEntityName:@"Recipe"]; |
| predicate = [NSPredicate predicateWithFormat:@"lastUsed <= %@", yearOld]; |
| [fetch setPredicate:predicate]; |
| request = [[NSBatchDeleteRequest alloc] initWithFetchRequest:fetch]; |
| [request setResultType:NSBatchDeleteResultTypeObjectIDs]; |
| |
| result = [moc executeRequest:request error:&error]; |
| if (!result) { |
| ALog(@"Failed on bulk delete: %@\n%@", |
| [error localizedDescription], [error userInfo]); |
| } |
| |
| [self mergeExternalChanges:[result result] ofType:NSDeletedObjectsKey]; |
| }]; |
| } |
The first difference, other than the fact that we’re using NSBatchDeleteRequest, is in the initialization of the request. NSBatchDeleteRequest is initialized with an NSFetchRequest rather than an entity name or description. This means we need to build an NSFetchRequest before we can initialize the NSBatchDeleteRequest. I prefer this approach because it matches what we are already accustomed to with NSFetchedResultsController.
Once the initialization of the NSBatchDeleteRequest is completed, the rest is the same. We call -executeRequest: error: against an instance of NSManagedObjectContext, which will be a blocking call, and then we can consume the results.
The NSBatchDeleteRequest has the same three types of results as the NSBatchUpdateRequest, so we can choose how to handle the results. Assuming we want to notify the rest of our application that some objects have been deleted, this implementation used the NSBatchDeleteResultTypeObjectIDs and handed off those NSManagedObjectID instances to the -mergeExternalChanges: ofType: method that we used previously.