Frederick C. Lee
Frederick C. Lee

Reputation: 9493

How do I empty an entire Core-Data Table?

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

Upvotes: 0

Views: 70

Answers (1)

justinpawela
justinpawela

Reputation: 1978

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.

Upvotes: 1

Related Questions