Core Data: Quickest way to delete all instances of an entity Core Data: Quickest way to delete all instances of an entity ios ios

Core Data: Quickest way to delete all instances of an entity


iOS 9 and later:

iOS 9 added a new class called NSBatchDeleteRequest that allows you to easily delete objects matching a predicate without having to load them all in to memory. Here's how you'd use it:

Swift 5

let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Car")let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)do {    try myPersistentStoreCoordinator.execute(deleteRequest, with: myContext)} catch let error as NSError {    // TODO: handle the error}

Objective-C

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Car"];NSBatchDeleteRequest *delete = [[NSBatchDeleteRequest alloc] initWithFetchRequest:request];NSError *deleteError = nil;[myPersistentStoreCoordinator executeRequest:delete withContext:myContext error:&deleteError];

More information about batch deletions can be found in the "What's New in Core Data" session from WWDC 2015 (starting at ~14:10).

iOS 8 and earlier:

Fetch 'em all and delete 'em all:

NSFetchRequest *allCars = [[NSFetchRequest alloc] init];[allCars setEntity:[NSEntityDescription entityForName:@"Car" inManagedObjectContext:myContext]];[allCars setIncludesPropertyValues:NO]; //only fetch the managedObjectIDNSError *error = nil;NSArray *cars = [myContext executeFetchRequest:allCars error:&error];[allCars release];//error handling goes herefor (NSManagedObject *car in cars) {  [myContext deleteObject:car];}NSError *saveError = nil;[myContext save:&saveError];//more error handling here


Reset Entity in Swift 3 :

func resetAllRecords(in entity : String) // entity = Your_Entity_Name    {        let context = ( UIApplication.shared.delegate as! AppDelegate ).persistentContainer.viewContext        let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: entity)        let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)        do        {            try context.execute(deleteRequest)            try context.save()        }        catch        {            print ("There was an error")        }    }


A little bit more cleaned and universal : Add this method :

- (void)deleteAllEntities:(NSString *)nameEntity{    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:nameEntity];    [fetchRequest setIncludesPropertyValues:NO]; //only fetch the managedObjectID    NSError *error;    NSArray *fetchedObjects = [theContext executeFetchRequest:fetchRequest error:&error];    for (NSManagedObject *object in fetchedObjects)    {        [theContext deleteObject:object];    }    error = nil;    [theContext save:&error];}