Reputation: 127733
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 ?
Upvotes: 2
Views: 2714
Reputation: 775
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()
}
}
Upvotes: 0
Reputation: 1602
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
Upvotes: 2