How to Delete All Core Data Entries and Reset Store in Swift

Written by

in

Quick answer: To reset Core Data, either remove the persistent store file and recreate it, or delete all objects. Removing the SQLite file via NSPersistentStoreCoordinator is fastest for a full reset. Use NSBatchDeleteRequest or a fetch-and-delete loop when you need to keep the store file or delete selectively.

Core Data has no TRUNCATE or DELETE FROM * call. If you want a Reset button that wipes all user data but keeps the model, you have to delete the objects or the underlying store file yourself.

Why this happens

Core Data is an object graph, not a SQL wrapper. The persistent store (usually a SQLite file) is managed by NSPersistentStoreCoordinator. There is no single API to “clear the database” because Core Data expects you to work with managed objects in a context and maintain referential integrity between entities.

That leaves you with two families of solutions. You can operate at the store level and delete the SQLite file itself, which is fast and atomic. Or you can operate at the object level and fetch and delete every NSManagedObject in each entity. Both work, but they have different trade-offs for speed, safety, and external files.

If your store uses allowsExternalBinaryDataStorage (Store in External Record File) introduced in iOS 5 / macOS 10.7, the SQLite file is not the only file on disk. Large binary attributes are stored in hidden external files next to the store. Deleting only the .sqlite file will leave those files behind.

How to fix it

Pick the approach that matches your goal: full reset vs. selective wipe. Do this work off the main thread if you have a lot of data, and save or merge changes back to the main context.

1. Remove and recreate the persistent store file (fastest full reset)

This is the recommended way for a true “reset to blank” button. You remove the store from the coordinator, delete the file from disk, then add the store back so Core Data recreates an empty file with the same model.

It is much faster than fetching every object, and it avoids faults and validation errors from partially deleted graphs. Use it when you want to delete everything.

Objective-C (as in the original pattern):

NSPersistentStore *store = persistentStoreCoordinator.persistentStores.firstObject;
NSError *error = nil;
NSURL *storeURL = store.URL;
NSPersistentStoreCoordinator *coordinator = persistentStoreCoordinator;

[coordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];

// Recreate an empty store at the same URL
[coordinator addPersistentStoreWithType:NSSQLiteStoreType
                          configuration:nil
                                    URL:storeURL
                                options:nil
                                  error:&error];

Swift with NSPersistentContainer:

import CoreData

func resetPersistentStore(container: NSPersistentContainer) throws {
    let coordinator = container.persistentStoreCoordinator
    guard let store = coordinator.persistentStores.first,
          let storeURL = store.url else { return }

    // 1. Remove store from coordinator
    try coordinator.remove(store)

    // 2. Delete file(s) from disk
    // For external binary storage, also delete external support directory if present
    if FileManager.default.fileExists(atPath: storeURL.path) {
        try FileManager.default.removeItem(at: storeURL)
    }
    // WAL and SHM files
    let walURL = URL(fileURLWithPath: storeURL.path + "-wal")
    let shmURL = URL(fileURLWithPath: storeURL.path + "-shm")
    try? FileManager.default.removeItem(at: walURL)
    try? FileManager.default.removeItem(at: shmURL)

    // External binary support folder: <storeName>_SUPPORT or .store_SUPPORT
    // If you use allowsExternalBinaryDataStorage, delete the sibling directory
    let supportURL = storeURL.deletingLastPathComponent()
        .appendingPathComponent("." + storeURL.deletingPathExtension().lastPathComponent + "_SUPPORT", isDirectory: true)
    try? FileManager.default.removeItem(at: supportURL)

    // 3. Recreate empty store
    try coordinator.addPersistentStore(ofType: NSSQLiteStoreType,
                                       configurationName: nil,
                                       at: storeURL,
                                       options: nil)

    // Reset contexts
    container.viewContext.reset()
}

Steps:

  1. Get the NSPersistentStore and its URL from persistentStoreCoordinator.persistentStores.
  2. Call removePersistentStore:error: / remove(_:) to detach it.
  3. Delete the file at storeURL.path with FileManager.default.removeItem(at:). Also delete -wal and -shm files.
  4. If you enabled allowsExternalBinaryDataStorage, delete the external records directory. Its name is not documented, so check the store’s directory after creation. The safest approach is to delete the whole support folder next to the store.
  5. Add the store back with addPersistentStore(ofType:at:options:). Core Data creates a new empty SQLite file.
  6. Call reset() on your contexts or recreate the container.

Do not just delete the file without removing the store from the coordinator first. The coordinator still holds an open connection and will fail to save.

2. Use NSBatchDeleteRequest (fast, keeps the store file)

If you want to keep the same SQLite file but empty its tables, use NSBatchDeleteRequest. It runs directly in the persistent store without loading objects into memory, so it is far faster than a fetch loop.

This is ideal when you cannot tear down the coordinator (for example, with NSPersistentCloudKitContainer or when other contexts are active).

import CoreData

func batchDeleteAllObjects(entityName: String, context: NSManagedObjectContext) throws {
    let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
    let request = NSBatchDeleteRequest(fetchRequest: fetch)
    request.resultType = .resultTypeObjectIDs

    let result = try context.execute(request) as? NSBatchDeleteResult
    if let objectIDs = result?.result as? [NSManagedObjectID] {
        let changes = [NSDeletedObjectsKey: objectIDs]
        NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [context])
    }
}

// Delete every entity in the model
func batchDeleteAllEntities(container: NSPersistentContainer) throws {
    let context = container.viewContext
    for entity in container.managedObjectModel.entities {
        guard let name = entity.name else { continue }
        try batchDeleteAllObjects(entityName: name, context: context)
    }
    try context.save()
}

Important details:

  • NSBatchDeleteRequest bypasses the context. You must merge the deletes back with mergeChanges(fromRemoteContextSave:into:) or reset the context, otherwise fetched objects will still appear in memory.
  • It does not fire validation rules or NSManagedObject delete rules in memory. Your delete rules in the model (Cascade, Nullify) are still applied in the store.
  • Run it on a background context if you are deleting a lot of data: container.performBackgroundTask { context in ... }.

To delete all entities, iterate managedObjectModel.entities and run a batch delete for each entity.name.

3. Fetch and delete entity by entity (selective and simple)

The oldest approach is to fetch every object for an entity and call deleteObject: / context.delete(_:). It is slower and uses more memory, but it lets you be selective and it respects in-memory validation.

Use it when you want to keep some entities (for example, keep Settings but delete Item and LogEntry).

import CoreData

func deleteAllObjects(entityName: String, in context: NSManagedObjectContext) throws {
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)
    fetchRequest.includesPropertyValues = false // only objectIDs, faster
    fetchRequest.includesSubentities = false

    let objects = try context.fetch(fetchRequest)
    for object in objects {
        context.delete(object)
    }
    if context.hasChanges {
        try context.save()
    }
}

Objective-C equivalent:

- (void)deleteAllObjectsForEntity:(NSString *)entityName inContext:(NSManagedObjectContext *)context {
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
    request.entity = entity;
    request.includesPropertyValues = NO;

    NSError *error = nil;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    for (NSManagedObject *obj in objects) {
        [context deleteObject:obj];
    }
    [context save:&error];
}

Tips for this method:

  • Set includesPropertyValues = false to avoid faulting large attributes.
  • Save once per entity, not once per object.
  • If you have relationships, delete in the correct order or rely on Cascade delete rules. Otherwise you will get referential integrity errors on save.
  • For large tables, fetch in batches with fetchLimit and fetchOffset to avoid memory spikes.

How to prevent it

  • Define delete rules in the data model. Use Cascade for owned children and Nullify for optional relationships so a full wipe does not leave dangling references.
  • Keep the reset logic in one place. Wrap it in a CoreDataResetService so a button, debug menu, and UI tests all call the same method.
  • If you use allowsExternalBinaryDataStorage, test your reset on a real device and verify the support directory is removed. Do not assume deleting the .sqlite file is enough.
  • After a reset, reset or recreate contexts. A viewContext that still holds deleted objects will show stale data until you call reset() or merge changes.
  • For production apps, guard the reset with confirmation UI and consider doing it in a background task. Deleting thousands of objects on the main thread will freeze the UI.

FAQ

Should I delete the SQLite file or delete objects one by one?

Delete the file (remove store + FileManager.removeItem + add store) if you want a complete, fast reset to empty. Delete objects with NSBatchDeleteRequest or a fetch loop if you need to keep the store file, keep some entities, or you are using CloudKit where tearing down the store is more complex.

Why do I still see data after NSBatchDeleteRequest?

The batch request deletes rows in the store but does not update objects already in memory. You must merge the result back into your contexts with NSManagedObjectContext.mergeChanges(fromRemoteContextSave:into:) or call context.reset() and refetch. Also make sure you saved the context that executed the request.

Does deleting the store file also delete external binary files?

No. When allowsExternalBinaryDataStorage is enabled, Core Data writes large binary attributes to external files in a hidden support folder next to the SQLite file. You must delete that folder as well, or use NSBatchDeleteRequest which cleans up the store correctly. The exact folder name is not public API, so verify the directory contents for your store URL after creation.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.