Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

ios - Is calling cellForRowAtIndexPath: ever practical?

I've seen many many developers when implementing a UITableViewDelegate and UITableViewDataSource directly call cellForRowAtIndexPath: to either:

1) Retrieve the cell to grab a model element that they stored within the cell:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MyCell *cell = (MyCell *)[tableView cellForRowAtIndexPath:indexPath];
    int secretCode = cell.secretCode;
    LaunchMissileViewController *vc = [[LaunchMissileViewController alloc] initWithSecretCode:secretCode];
    [self.navigationController pushViewController:vc];
}

2) Attempt to style the cell (this has clear problems, but seems very common):

MyCell *cell = (MyCell *)[self cellForRowAtIndexPath:indexPath];
// or [tableView cellForRowAtIndexPat:indexPath];
cell.backgroundColor = [UIColor greenColor];

Is it safe to make the blanket statement that "only the framework should ever call cellForRowAtIndexPath:"? Or is there a practical reason one might ever call it themselves?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Personally I don't think there are ever good cases to directly call tableView:cellForRowAtIndexPath: directly on the data source.

For case #1 it is simply bad coding. The cell should never contain the data. The data source should have the data so get the data from the actual data source, not the cell.

For case #2 you would only ever need to update a visible cell. And for this you can use the UITableView cellForRowAtIndexPath: method. No need to call the data source for the cell.

I try never to say "never" but it should be an extremely rare case where you have a real need to get the cell by calling the data source method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...