dequeueReusableCellWithIdentifier:forIndexPath: VS dequeueReusableCellWithIdentifier:

Viewed 3635

I have read this question and think that I understand the difference between the two methods until I find a strange example:

Set table view cell's style be Basic, Identifier be Cell in Storyboard, code as below:

import UIKit

class TableViewController: UITableViewController {
    var items: [String]!

    override func viewDidLoad() {
        super.viewDidLoad()
        items = ["first", "second", "third"]
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // either works fine
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! // let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

        cell.textLabel?.text = items[indexPath.row]
        return cell
    }
}

enter image description here

Very simple, but when I change the tableView:cellForRowAtIndexPath: method to 1, 2, 3, 4 cases respectively:

Case 1:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
    cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

    cell.textLabel?.text = items[indexPath.row]
    return cell
}

Case 2:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
    cell = tableView.dequeueReusableCellWithIdentifier("Cell")!

    cell.textLabel?.text = items[indexPath.row]
    return cell
}

Case 3:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
    cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

    cell.textLabel?.text = items[indexPath.row]
    return cell
}

Case 4:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
    cell = tableView.dequeueReusableCellWithIdentifier("Cell")!

    cell.textLabel?.text = items[indexPath.row]
    return cell
}

Case 1, 2 (doesn't work):

enter image description here

Case 3, 4 (works fine):

enter image description here

How to explain? I think it really helps to understand these two methods from another perspective, any opinion is welcome.

2 Answers
Related