Core Data - removing items
-
21-06-2021 - |
문제
I have a question due to some doubts about some of my code. In an array of NSManagedObject I need to get rid of some of them. Here is (below) the code I use. I have to say it works, within my range of experience. So my question is more to make sure I am not doing something wrong rather than to solve an existing problem
for (NSManagedObject *item in objects) {
if ([[item valueForKey:@"OK"] intValue]>1) {
[context deleteObject:item];
continue;
}
}
Since I am modifying the content of the array "objects" while looping on it, I fear that my code is kind of unsafe. Of course it all depends on how things are handled behind the scene, which I do not know.
Thanks.
해결책
When you call deleteObject:
you are flagging an object for deletion, not deleting it immediately, and certainly not deleting it from the collection that you are iterating during the iteration.
From the docs:
Specifies an object that should be removed from its persistent store when changes are committed.
If you inspect the deleted items after the deleteObject:
call you will see the objects still exist but have their isDeleted
flags set to YES
. The object will actually be deleted when the NSManagedObjectContext
is next saved.
다른 팁
You are only flagging the item for deletion with your deleteObject
line. In order to force the context to execute the deletion, run this at the bottom of your function:
NSError *error;
if (![context save:&error]) {
return;
}