正在调用cellForRowAtIndexPath:有没有实际的?

我在实现UITableViewDelegateUITableViewDataSource直接调用cellForRowAtIndexPath:见过许多开发人员:

1)检索单元格以获取它们存储在单元格中的模型元素:

 -(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)试图devise细胞(这有明确的问题,但似乎很常见):

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

“只有框架应该调用cellForRowAtIndexPath: ”这个覆盖语句是否安全? 或者有没有一个人可能会自称的实际理由?

就个人而言,我不认为有直接调用tableView:cellForRowAtIndexPath:直接在数据源上的好例子。

对于案例#1,它只是坏的编码。 单元格不应包含数据。 数据源应该有数据,以便从实际数据源获取数据,而不是单元格。

对于案例#2,你只需要更新一个可见的单元格。 为此,您可以使用UITableView cellForRowAtIndexPath:方法。 无需调用单元格的数据源。

我尽量不要说“从不”,但是如果您真的需要通过调用数据源方法来获取单元格,则应该是极其罕见的情况。

我会说rmaddy是正确的,虽然我有一个案例可以说是可行的使用:

如果您需要 UITableViewCell的副本应用到另一个视图。

(来自https://github.com/Ice3SteveFortune/i3-dragndrop

 UIView* cellCopy; UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath]; NSData* viewCopyData = [NSKeyedArchiver archivedDataWithRootObject:cell]; cellCopy = [NSKeyedUnarchiver unarchiveObjectWithData:viewCopyData]; // Maybe to drag-and-drop outside of the UITableViewCell. [self.otherView addSubview:cellCopy]; 

我想在这里作为less数情况下的一个例子, 远程实际地调用cellForRowAtIndexPath:

从单元中检索数据是没有意义的,因为插入到单元中的数据将被开发人员所知晓。 开发人员可以直接获取数据。 另一个问题是,如果这个单元格不可见,它将首先生成,然后检索数据。