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?
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)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.