1
votes

It is okay to add or delete single object in NSManagedObjectContext,just wonder why there is no API to clear all objects one time in NSManagedObjectContext ?

Specifies an object that should be removed from its persistent store when changes are committed.

  • (void)deleteObject:(NSManagedObject *)object

Why there is no API such as clearAllObjects to delete all objects at one time ?

2

2 Answers

2
votes

Yes its fine to do so using the deleteObject: method. If you want to delete all objects it might be quicker to destroy your managed object context, delete or change your presistent store and recreate your core data stack

0
votes

This may be a simple way to get the results you're looking for with one call. It does require multiple fetch and delete requests, but you don't need to manually list each entity name.

extension NSManagedObjectContext {
    func clearAll() {
        persistentStoreCoordinator?.managedObjectModel.entities.compactMap({ $0.name }).forEach { entity in
            let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entity)
            try? fetch(fetchRequest).forEach({ delete($0) })
        }
        try? save()
    }
}