Chapter 18 final/start source code is the same?

I am following along with Chapter 18 - User Defaults and I am having an issue with the code to create a UITableViewCell that has the subtitle. I tried looking at the final code for the chapter, but for AllListsViewController.tableView(_:cellForRowAt:) it looks the same as the starter.

Is that right?

The issue I am having is with this code (at least this is what I think it’s supposed to say based on the chapter so far):

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: UITableViewCell!
    if let c = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) {
        cell = c
    } else {
        cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier)
    }
    
    let checklist = dataModel.lists[indexPath.row]
    cell.textLabel!.text = checklist.name
    cell.accessoryType = .detailDisclosureButton
    
    cell.detailTextLabel!.text = "\(checklist.countUncheckedItems()) Remaining"
    
    return cell
}

The issue specifically is that the app crashes on the call to:

cell.detailTextLabel!.text = "\(checklist.countUncheckedItems()) Remaining"

Which makes sense, since the else above never gets executed and the detailTextLabel will be nil as a result.

I was hoping to look at the final code to understand what I am doing wrong (read: I am not looking for help here, just want to know if the code is correct for the final sample code).

Here is what that method says in the final project:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
    // Update cell information
    let checklist = dataModel.lists[indexPath.row]
    cell.textLabel!.text = checklist.name
    cell.accessoryType = .detailDisclosureButton
    return cell

}

Thanks in advance.

Ahhh, I figured it out.

I didn’t do this:

➤ Go to AllListsViewController.swift and remove the register(_:forCellReuseIdentifier:) line from viewDidLoad since we will not require that. Instead, we will create the table view cells by hand if a cached cell is not available.

The question remains if the final source code for Chapter 18 is right since it looks the same as the starter sample.

I just checked and the two versions of code are different since there are other changes to AllListsViewController.swift and DataModel.swift in the final version. However, you are correct about the table cell registration not being removed in the final version of the source code. Not quite sure why not except that it was probably an oversight on my part …

Thanks! No worries I was able to catch my own error. :slight_smile: Appreciate the whole tutorial!

This topic was automatically closed after 166 days. New replies are no longer allowed.