0

I need to be able to clear a simple stand-alone (non-relational) table. Is there a simple command/verb to do this?

Frederick C. Lee
  • 9,019
  • 17
  • 64
  • 105

1 Answers1

1

By "clear a table" I assume you mean delete all Entities of a specific type. The only way is to fetch them all and delete.

I will refer you to this answer, however I will translate to Swift below.

Assumes you have an NSManagedObjectContext named context:

let fetchRequest = NSFetchRequest(entityName: "myEntity")
fetchRequest.includesSubentities = false

if let objects = context.executeFetchRequest(fetchRequest, error: nil) as? [NSManagedObject] {
    for each in objects {
        context.deleteObject(each)
    }
}

context.save(nil)

Please note that I completely ignored error handling, so you'll want to check for errors too as you go.

Community
  • 1
  • 1
justinpawela
  • 1,968
  • 1
  • 14
  • 18