iOS UITableView: what's the different between "cellForRowAtIndexPath" and "willDisplayCell: forRowAtIndexPath:"

Solution 1:

You are right, cell configuration can (in theory) be done in both methods.

However, almost all UITableView have a data source which implements cellForRowAtIndexPath: (it is a required method in the protocol). On the other hand, the willDisplayCell:forRowAtIndexPath: (which is a method of the delegate, not the data source) is optional.

As configuring a cell is usually dependent on the data you want to show, cellForRowAtIndexPath: is by far the most common place to do cell configuration. (I can't even remember using willDisplayCell:forRowAtIndexPath:).

There's one notable exception: when you are using a storyboard and static cells (instead of cell prototypes), you can't do anything useful in cellForRowAtIndexPath: (because dequeueReusableCellWithIdentifier: returns nil), so you have to do configuration in willDisplayCell:forRowAtIndexPath:, viewWillAppear: or other methods.

@NSDeveloper: you're right. Thanks for the hint.

Solution 2:

cellForRowAtIndexPath should actually return a cell instance. It should be a re-used cell, when possible. This method is required for the UITableViewDataSource Protocol. This is normally where you select the data that will be displayed in the cell. With dynamic cells, it's common to set UI properties such as selected state at the same time you set the data here.

willDisplayCell is optional and is called after. This is your last chance to customize the cell before it's displayed. At this point, the cell instance has already been created. You can change things like selected state, etc. here. You should not be changing the data/structure of the cell or instantiating anything new, but only changing the state of UI properties for the cell. This is commonly used with static cells.