'SwiftUI delete core data
I have written a delete all function in SwiftUI. It compiles but fails when running on the simulator.
@Environment(\.managedObjectContext) var context
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "InvItem")
// Create Batch Delete Request
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try context.execute(batchDeleteRequest)
} catch {
// Error Handling
print("Did not clear core data")
}
}
The error is as follows: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSPersistentStoreCoordinator for searching for entity name 'InvItem'' terminating with uncaught exception of type NSException
Can someone help?
Solution 1:[1]
You have to execute the fetch request on the persistent store coordinator
@Environment(\.managedObjectContext) var context
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "InvItem")
// Create Batch Delete Request
let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
let persistentStoreCoordinator = context.persistentStoreCoordinator!
do {
try persistentStoreCoordinator.execute(batchDeleteRequest, with: context)
} catch {
// Error Handling
print("Did not clear core data", error)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vadian |
