Search code examples
iosswiftcore-data

Why do we need to call context.delete to delete an item from NSManagedObject array?


Suppose I have;

var itemArray = [Item]()

and Item is a NSManagedObject. Item has two attributes "Title":String and "Done":Boolean. Here is the picture of my data model.

enter image description here

//  Item+CoreDataClass.swift

//  This file was automatically generated and should not be edited.
//

 import Foundation
 import CoreData

 public class Item: NSManagedObject {

 }

When I change the value of Done and call context.save, it is automatically reflected to Persistent Container. However, when I remove an element from array by saying,

itemArray.remove(at: someindex)

and call context.save. The item is not deleted from Persistent Container. Only if I called,

context.delete(itemArray[someindex])

then the item is truly deleted from store.

So why only removing from itemArray and save context is not sufficient although changing an attribute' value and save context is sufficient for successful CRUD operation on Core Data?


Solution

  • When you change an attribute on an Item object then Core Data (actually the NSManagedObjectContext) detects that since the Item belongs to the NSManagedObjectContext and the item is marked as dirty. But your array has no connection to the NSManagedObjectContext in any way so any changes you make it to remains undetected by the NSManagedObjectContext and that is why you need to tell it explicitly that you want to delete the item you removed from the array.

    Another way to look at it is that anything you create/define in your Core Data model is known by NSManagedObjectContext but anything created outside in swift code is unknown. If you start working with to-many relationships between entities you will see that then adding or removing objects from the to-many collection will be handled directly by the NSManagedObjectContext in a way you expected for your array.