Table View State Restoration

If a UITableView participates in state saving and restoration, the restoration mechanism would like to restore the selection and the scroll position. However, it would prefer not to do this on the basis of mere numbers — the table view’s contentOffset, or a row number — because what is meaningful in a table is not a number but the data being displayed. There is a possibility that when the app is relaunched, the underlying data may have been rearranged somehow; and the restoration mechanism would like to do the right thing nevertheless.

The problem is that the state saving and restoration mechanism doesn’t know anything about the relationship between the table cells and the underlying data. So you have to tell it. You adopt the UIDataSourceModelAssociation protocol and implement two methods:

modelIdentifierForElementAtIndexPath:inView:
Based on the index path, you return some string that you will later be able to use to identify uniquely this bit of model data.
indexPathForElementWithModelIdentifier:inView:
Based on the unique identifier you provided earlier, you return the index path at which this bit of model data is displayed in the table now.

Devising a system of unique identification and incorporating it into your data model is up to you. In the TidBITS News app, for example, it happens that my bits of data come from a parsed RSS feed and have a guid property that is a global unique identifier. So implementing the first method is easy:

- (NSString ...

Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.