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

Time:11-24

Suppose I have;

var itemArray = [Item]()

and it is NSManagedObject. Item has two properties "Title":String and "Done":Boolean.

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 properties and save context is sufficient for successful CRUD operation on Core Data?

CodePudding user response:

The array var itemArray = [Item]() has no direct relation with the underlying database. Therefore removing items from that array doesn't affect the Core Data database.

To create, save or delete NSManagedObject instances in a Core Data database you need to call the related functions of a valid NSManagedObjectContext.

CodePudding user response:

Any operation on CoreData should be done through NSManagedObjectContext as it is the scratchpad to access or update any entity in database. So in your case while deleting the Item entity, you should do that through context only to get reflected on database.

var itemArray = [Item]()
let context = //get your context
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Item")
let predicate = NSPredicate(format: " (primaryKey == %@) ", "your_primary_key")
fetchRequest.predicate = predicate
itemArray = try! context.fetch(fetchRequest)
for i in 0 ..< itemArray.count where i < itemArray.count-1 {
    context.delete(itemArray[i])
}

do {
    try context.save()
} catch {
    // print the error
}
  • Related