Core Data: Setting attribute of deleted object causes it to remain in store
Core Data: Setting attribute of deleted object causes it to remain in store
- Subject: Core Data: Setting attribute of deleted object causes it to remain in store
- From: Jerry Krinock <email@hidden>
- Date: Thu, 03 May 2012 17:19:20 -0700
I use Core Data to model an ordered tree of objects. Delete Rule from parent to children is Cascade. Because this is pre-Lion, ordering is done by my own 'index' attribute. Store type is In Memory.
Deleting children with many siblings was expensive because, as each child was deleted, business logic would require all of its siblings to be re-indexed to fill the gap, maybe triggering KVO in user interface, etc., etc.
To improve performance, I implemented a bulk "deleteObjects:" method, which does this…
• Loop 1. For each deletedObject,
Add parent to set of affectedParents
If deletedObject is itself in affectedParents, remove it
Remove from parent with this:
NSMutableSet* oldSiblings = [oldParent mutableSetValueForKey:@"children"] ;
[oldSiblings removeObject:deletedObject] ;
Inadvertently (needed in other cases) set an attribute in deletedObject,
[deletedObject setIndex:[NSNumber numberWithInteger:0] ;
Delete from managed object context with this:
[managedObjectContext deleteObject:object] ;
[managedObjectContext processPendingChanges] ;
• Loop 2. For each affectedParent,
Re-index its children to remove gaps
This improved the performance nicely, but led to the unexpected result that any objects which happened to have been deleted (in Loop 1) after their parent had been deleted remain in the store, with all attributes nil. In other words, a bunch of "nil" objects.
Branching around the inadvertent setIndex: fixed the problem.
I've seen the nilling of attributes happen before, upon re-inserting a deleted object [1]. This behavior is obviously related, but different. If anyone can think of a good reason for this behavior, it would be interesting to read.
Jerry Krinock
1. http://www.cocoabuilder.com/archive/cocoa/236009-nsmanagedobjectcontext-insertobject-cancels-prior-deletion.html?q=cancels+prior+deletion#236009
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden