CausticMango

software for fun & profit

Sidebar
Menu

I Love You, Xcode

Auto incrementing build numbers. See what happens when you use a real, Unix-based OS?

Pasted Graphic 1

Adventures in CoreData

While changing one of my iOS apps to use an NSFetchedResultController instead of a sorted NSArray of NSManagedObject instances (I really like the way it handles sorting and grouping, additions and deletions). Trouble is, the list is manually sortable by the user using the drag controls in edit mode.

Pasted Graphic

The way you do this, of course, is by adding a numeric "sort" attribute to the entity and sort by it. When you move a row, you renumber the rows by their sort attribute.

If you've ever tried to do this with a UITableViewController using an NSFetchedResultController, you'll no doubt be shaking your head right now because you'll know this leads to very strange results. Do a search online and you'll find tons of detailed advice for how to resolve this "problem".

All of it is wrong. Tragically, comically, desperately wrong. Alway, always, always read the documentation first!

It turns out the cause of the odd behavior is very simple; the controller is observing the entities, recognizing changes, and translating them to table updates by calling the delegate methods. Normally, this is exactly what you want. The table will automatically adjust to changes in the fetched data. Except, if the table itself initiates the change, the two mechanisms compete with each other.

The solution to this strange behavior is simply ignore the delegate callbacks if the changes come from the table being edited. Set a flag in the tableView:moveRowAtIndexPath:toIndexPath: callback and if set, bail out of the NSFetchResultControllerDelegate methods.

Just goes to show you; don't trust the Internet. Especially for coding advice.