Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: What is a difference between dequeueReusableCell(withIdentifier:for:) and dequeueReusableCell(withIdentifier:)?

According to the official documentation, there are two ways to get a reusable cell from a queue of a tableView. One is dequeueReusableCell(withIdentifier:for:) and another is dequeueReusableCell(withIdentifier:). Assuming from the explanation of the document, I think the former is the method that returns the reusable cell and adds it to tableView. On the other hand, the latter is the method that just returns the reusable cell. Is this right?

If it is right, I have another question.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: UITableViewCell = self.tableView.dequeueReusableCell(with: SomeTableViewCell.self, for: indexPath)
    let anotherCell: UITableViewCell = self.tableView.dequeueReusableCell(with: AnotherTableViewCell.self)
    return anotherCell
}

At first line, we can get the reusable cell and add the cell to the tableView. And at the second one, we just obtain another reusable cell. Finally, the method returns the cell obtained from the second line. The returned cell is different with the cell being having added to the tableView already. In this case, the cell added to tableView at first line is just replaced by the returned cell at the final line? Thanks.

like image 558
Kazuya Tomita Avatar asked May 27 '17 06:05

Kazuya Tomita


1 Answers

Method dequeueReusableCell(withIdentifier:) is older than dequeueReusableCell(withIdentifier:for:), and the main difference between them is that first will return nil, if cell don't registered, the second will throw an exception, and an app will crash. IndexPath requires for height calculation(if defined tableView:heightForRowAtIndexPath)

like image 107
Stan H Avatar answered Nov 09 '22 13:11

Stan H