How to delete an NSManagedObject in Core Data

- by

You can delete individual objects by using the NSManagedObjectContext method deleteObject, like so:

[self.managedObjectContext deleteObject:yourManagedObject];

To delete all managed objects from your store, you can use a for-in loop:

- (void)clearCoreData {
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"YourEntity" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"Could not delete Entity Objects");
    }
    
    for (YourEntity *currentObject in fetchedObjects) {
        [self.managedObjectContext deleteObject:currentEntity];
    }
    
    [self saveContext];

}

I assume that you have created managed object sub classes. I’m also assuming that you have access to save the context. If not, here’s what the method looks like (taken from AppDelegate with Core Data template):

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {

            NSLog(@"Saving didn't work so well.. Error: %@, %@", error, [error userInfo]);
            abort();
        }
    }
}


If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.