cellForRowAtIndexPath and Cell Configuration
O开发者_运维百科kay, so consumate with the standard template code for UITableViewController, I've been using cellForRowAtIndexPath:
to set up my UITableViewCells based on the data source.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//cell setup
cell.textLabel.text = @"Initial Data!";
return cell;
}
However, this is suddenly striking me as a problematic practice. For instance, lets say I want to do this
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//some processing or data update is done here
//now I want to update the cell
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.text = @"New Data";
}
It seems like this is wasteful code, because retrieving the cell to update it, is causing it to be updated a second time from the code in cellForRowAtIndexPath.
So should I be putting the configuration for the cell somewhere else and calling it some other way, or should I be writing the configuration in cellForRowAtIndexPath
in a more clever way so that a simple call to it will update the UI withou
Maybe altering the data is a better idea.
I'm assuming you will get your data from an array? Then alter the data in the didSelectRowAtIndexPath method and reload just the selected cell.
Generally I keep a self array to apply necessary data to cell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//cell setup
MyObject *obj = ...; ///< retrieve obj from somewhere
cell.textLabel.text = obj.text;
return cell;
}
Then, when selected, I will modify my data source.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *newData = @"New Data"; ///<
// Update data source
MyObject *obj = ...;
obj.text = newData;
// Update UI
....
}
I prefer to make MyObject to handle things about data processing, for example, obtain a thumbnail for cell in a thread, or calculate complexity result. Controller will combine data and UI.
精彩评论