ios - How do i correctly handle context.rollback() with an NSFetchResultsController -


i have nsfetchresultscontroller provides data uitableview. have add button in navigation bar lets user add new entity in next view.

in next view create new entity , insert context. user can save change. however, if user decides not keep new entity, can hit cancel , call context.rollback() rid of new entity. causes fetchresultscontroller throw exception:

terminating app due uncaught exception 'nsinternalinconsistencyexception', reason: 'invalid update: invalid number of rows in section 0. number of rows contained in existing section after update (2) must equal number of rows contained in section before update (2), plus or minus number of rows inserted or deleted section (0 inserted, 1 deleted) , plus or minus number of rows moved or out of section (0 moved in, 0 moved out).

this error shown when have 2 entities, , create third 1 , hit cancel.

the exception thrown right perform rollback, on other view. perform insert following code:

 let entity =  nsentitydescription.entityforname("template",             inmanagedobjectcontext: context!)  let newtemplate = nsmanagedobject(entity: entity!, insertintomanagedobjectcontext: context) as! template          newworkouttemplate.setvalue("new template", forkey: "name")          self.template = newwtemplate 

i set undo manager of context before performing insert. why nsfetchresultscontroller not detect insertion of new entity, detects deletion when perform rollback? because both insert , deletion performed on same entity?

i realized had didchangeobject fetchresultcontrollerdelegate method implemented in original vc, , culprit. line

            templatestable.deleterowsatindexpaths([indexpath!], withrowanimation: uitableviewrowanimation.fade) 

was being called when other vc called context.rollback()

so solved adding bool inanother first vc. set false. when segue other view, set true. then, when rollback happens in other view, fetchcontroller's didchangeobject called. within didchangeobject, check if i'm in other view, , not if am:

if (!inanother && type == nsfetchedresultschangetype.delete) {          templatestable.deleterowsatindexpaths([indexpath!], withrowanimation: uitableviewrowanimation.fade)  } 

also, set inanother false in first vc's viewwillappear() make sure row deletions continue functioning properly.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -