KarolisShp KarolisShp - 7 months ago 50
Swift Question

Core Data deleting one element NSManagedObject Swift

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

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


To delete element from managedObjectContext...

do {
      try appDelegateObj.managedObjectContext.save()
} catch {
      let saveError = error as NSError

Here one tutorial that have complete CRUD (Create, Read, Update and Delete) operation described.

You have to see that. This is very simple.

Reference Link