Swift NSManagedObjectContext Extension to Delete All Core Data Objects

I made this NSManagedObjectContext extension so that I could delete all of a users data when they log out of the app I’m writing. The alternative was to delete the sqlite file itself and reinitialize my Core Data stack, but that seemed potentially more problematic and less safe.

The two instance methods on NSManagedObjectContext for deleting objects are:

  • func deleteAllObjects(error: NSErrorPointer)
    • Delete all objects in a context. Bails out and returns an error if there’s any problems.
  • func deleteAllObjectsForEntity(entity: NSEntityDescription, error: NSErrorPointer)
    • Delete all objects of an entity type. Bails out and returns if there’s an error.

I also included a convenience initializer for creating a new context with a parent. The way I use the deletion methods would be to create a private queue child context, block out the UI while this is going on with an activity indicator or something, and then call deleteAllObjects(_:) on the child. If there’s an error, you can just throw away the child context, and otherwise save your main context and commit it back to the store. Like this:

Here’s the code for the extension: