开发者

Updating a cell in UITableViewController after changes in a DetailViewController

I have a fairly simple setup: RootViewController (which is a UITableViewController). Each cell in开发者_StackOverflow it shows some stats for a different person. You can tap on any of these cells to push on a DetailViewController (UIViewController), and modify the stats (which are stored in a model object). After the user is done modifying the stats for that person, they click the Back button, causing popViewControllerAnimated to get called.

My question is: What's the best way to know in the RootViewController that the stats for this player have been changed, and updated the cell accordingly? Do I have to record in the RootViewController which cell was tapped, and then call the appropriate setNeedsDisplay after the DetailViewController completes? And if so, which method should I do this from? viewWillAppear?

Or is there a nicer way? This seems like it'd be a fairly common task, and that I'm missing something obvious.


This depends on how your model is designed and whether or not you're using Core Data.

The basic principle is to observe the properties of your model objects that might change in the detail views. When something changes in the detail controller, somehow mark its table cell as dirty. Then, when the table view becomes visible again, get the changed cell with [tableView cellForRowAtIndexPath:] and reconfigure the cell. The cellForRowAtIndexPath: method will handily return nil if the cell is not visible which will keep you from spending time updating cells that don't need it.

If you're using Core Data (and you probably should be), NSFetchedResultsController does almost all of this work for you. It will observe your model objects and send the controller:didChangeObject:atIndexPath:forChangeType:newIndexPath: message to its delegate for each changed cell. Then, you can make the proper changes to the table view.

I recommend creating a new Xcode project using the Navigation-based Application template with the Use Core Data for Storage checkbox ticked. The template has a good default implementation of the aforementioned pattern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜