Deleting from Core Data

Deleting objects from Core Data should not be recognized as deleting rows from SQLite table. It is like deleting objects from Object Graph. This is an example of deleting all rows for the current file number. I retrieve all NSManagedObject objects and delete them in cycle.

+ (BOOL)deleteScrollPositionsForFileNumber:(NSInteger)fileNumber {
    BOOL success;
    NSManagedObjectContext *context = appDelegate.managedObjectContext;
    if (context == nil) {
        NSLog(@"Error: No context");
        success = NO;
        return success;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"fileNumber == %d", fileNumber];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ScrollPosition" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    [fetchRequest setPredicate:predicate];
    NSError *error = nil;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    NSLog(@"Number of deleted objects: %d", [fetchedObjects count]);
    for (NSManagedObject *object in fetchedObjects) {
        [context deleteObject:object];
    success = YES;
    return success;

Leave a Reply

Your email address will not be published. Required fields are marked *