Search code examples
iosswiftuikittableview

Difference between: tableView.cellForRow and dataSource.cellForRowAtIndexPath


currently I am working on a project and the developers who started the project used to access the cells with

dataSource.cellForRowAtIndexPath(indexPath)

but I am used to access cells with

cellForRow(at: indexPath)

Does anyone know the difference and which is better to use? The reason i ask is that dataSource.cellForRowAtIndexPath(indexPath) caused us this crash.

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Attempted to dequeue multiple cells for the same index path, which is not allowed. If you really need to dequeue more cells than the table view is requesting, use the -dequeueReusableCellWithIdentifier: method (without an index path). Cell identifier: CheckTableViewCell, index path: {length = 2, path = 1 - 0}'


Solution

  • The difference is this:

    dataSource.cellForRowAtIndexPath(indexPath)
    

    cellForRowAtIndexPath is a method that your dataSource provides to the UITableView. It is called by iOS to load a cell for a specific indexPath. It works by dequeueing a reusable cell and filling in the information for that cell.

    You typically do not call this. iOS does.

    cellForRow(at: indexPath)
    

    This method is provided by iOS to return the cell for a specific indexPath if that cell is currently on screen, or nil if the cell isn't on screen.

    This method is for you to call if you have an indexPath and you need the associated cell.


    Your error is happening because you are calling cellForRowAtIndexPath which dequeues a reusable cell to do its job. The cell is already on screen and already has a cell associated with it, so now there are two, which makes no sense.