Re-ordering Core Data Objects on iOS4

The Core Data framework on the iPhone is incredibly powerful. It’s also incredibly efficient and part of that is because a collection of objects only have the order that you implicitly give them. For example you typically might give an Event object a timestamp and when you pull out all the events you might sort on that timestamp.

The NSFetchedResultsController is the main power house when dealing with such a scenario and is great for the master part of a master/detail data relationship. Its main purpose is to manage the results returned from a fetch request similar to the above and provide data for a UITableView via delegate methods. It reacts on the model level so if you delete an Event object, the NSFetchedResultsController informs its delegate and so updates the UITableView automatically. It’s very clever indeed!

As I found out earlier yesterday, the problem comes when you want to re-order the objects in a user-defined way. Instead of sorting on a timestamp, I wanted the user to be able to specify that one object should occur before the other… I’m working on an app that lets you place waypoints down on a map. Timestamps in waypoints aren’t much use. It’s much more critical that they have a specific order.

After some Googling I came across a useful article on CocoaIsMyGirlfriend. This helped me 90% of the way but I had problems when re-ordering. When you re-order the objects, the UITableView would move cells about seemingly at random. This is because NSFetchedResultsController is model-driven. When you re-order something using the tableview methods the view is already correct (because you’ve dragged and dropped the cell there – it’s a user-driven change) and so when the delegate detects your index changes, it walks all over your view believing the cells to be in their original position. The trick is to ‘disable’ the UI updates with a boolean in your delegate methods. Set the boolean just before your re-indexing and unset it afterwards.

For an example, see this stack overflow link on re-ordering.

Also have a look at what the Apple docs say on user-driven updates on the NSFetchedResultsController.