Reputation: 119
So I was trying to delete an element from CoreData and followed other answers in Stackoverflow. Here's the code to delete an element from datamodel when the button is clicked
moneyManager.moneys.removeAtIndex(indexPath.row)
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDel.managedObjectContext
do {
context.deleteObject(moneyManager.moneys[indexPath.row] as! NSManagedObject)
try context.save()
}catch {
print("Error not saved")
}
There is an error that I get:
Cast from 'money' to unrelated type 'NSManagedObject' always fails
Now I have seen other people using arrays of AnyObject?, yet I don't understand where this array should specifically come from and where I should declare it.
moneyManager is class that has an array of moneys which stores data of every money transaction done by the user. I think I should delete data not from here but from the entity itself, am I right?
Thanks in advance
Upvotes: 1
Views: 570
Reputation: 2297
To delete element from managedObjectContext...
appDelegateObj.managedObjectContext.deleteObject(dataArray[indexPath.row])
do {
try appDelegateObj.managedObjectContext.save()
dataArray.removeAtIndex(indexPath.row)
} catch {
let saveError = error as NSError
print(saveError)
}
Here one tutorial that have complete CRUD (Create, Read, Update and Delete) operation described.
You have to see that. This is very simple.
Upvotes: 1