I am working on an app written in Swift that uses Core Data. For it to work correctly, I need to delete all the objects in Core Data for a specific entity and key. I have been able to find many different questions covering deleting from core data, but as far as I can tell none of them only delete objects for a specific key.
My current code follows a similar style to the "Fetch, Delete, Repeat" method in this article. It talks about an iOS 9 updated way to do this with NSBatchDeleteRequest
, but I have not discovered any way to make either of these only delete the values for a specific key.
Current Delete Code (I have tried to add a key to the object, but it throws an error about not being able to cast NSCFNumber
to NSManagedObject
at runtime)
getContext().delete(object.value(forKey: key) as! NSManagedObject)
Full Code Pertaining to Core Data
func getContext () -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
func coreDataReplaceValue(entity: String, key: String, value: Int) {
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: entity)
do {
let searchResults = try getContext().fetch(fetchRequest)
for object in searchResults as! [NSManagedObject] {
getContext().delete(object.value(forKey: key) as! NSManagedObject)
}
} catch {
print("Error with request: \(error)")
}
let context = getContext()
let entity = NSEntityDescription.entity(forEntityName: entity, in: context)
let accelerationLevel = NSManagedObject(entity: entity!, insertInto: context)
accelerationLevel.setValue(value, forKey: key)
do {
try context.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
}
Other questions I have looked at that pertain to my question, but don't include a way to add a key:
Swift 3 Core Data Delete Object
delete core data managed object with Swift 3
This last one looked promising at first, but the code changes it into an NSManagedObject, so I don't think it holds the solution.
Deleting first object in Core Data (Swift)
Thanks for any help!
Taylor