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:
If you inspect the deleted items after the
deleteObject:call you will see the objects still exist but have theirisDeletedflags set toYES. The object will actually be deleted when theNSManagedObjectContextis next saved.