Core Data: Setting attribute of deleted object causes it to remain in store

  • 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-ins
    ertobject-cancels-prior-deletion.html?q=cancels+prior+deletion#236009
  • On 3 May 2012, at 7:19 PM, Jerry Krinock wrote:

    > 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.

    By the database rules, the record that backs a managed object may be deleted, but by the memory-management rules, the managed object that wraps the record must remain until it is dealloced. Core Data represents this state by turning the managed object into an irrecoverable fault.

    — F
previous month may 2012 next month
MTWTFSS
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      
Go to today