rpbones531
rpbones531

Reputation: 23

Break error while creating a calendar

Pic of error

Have break error Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode==0x0). No errors with build, just when run, have a break

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let calendars = self.calendars {
        return calendars.count
    }
    return 0

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!

//error happens here

    if self.calendars != nil {
    let calendarName = self.calendars?[(indexPath as NSIndexPath).row].title
        cell.textLabel?.text = calendarName
    } else {
        cell.textLabel?.text = "Unknown Calendar Name"
    }
    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destinationVC = segue.destination as! UINavigationController
    let addCalendarVC = destinationVC.viewControllers[0] as! AddCalendarViewController
    addCalendarVC.delegate = self
}
func calendarDidAdd() {
    self.loadCalendars()
    self.refreshTableView()
}

}

Upvotes: 1

Views: 53

Answers (2)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52103

tableView.dequeueReusableCell(withIdentifier: "Cell")!

You are unwrapping an optional value which might be nil in the first place. Cell might not have been created yet especially if you haven't registered the cell's class with that identifier so it'll crash first time table tries to populate the cell. You should first check if cell is nil:

var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
  cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
}
...

Upvotes: 1

Forest Kunecke
Forest Kunecke

Reputation: 2160

The immediate red flag I see is here:

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!

When dequeueing reusable cells, I like to wrap them in guard statements, so my app doesn't crash. It also tells me a bit more information when something does go wrong:

guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") else {
    print("couldn't dequeue a reusable cell for identifier Cell in \(#function)")
    return UITableViewCell()
}

This crash could be for a few reasons. You may have forgotten to register the reuse identifier, but if you're using storyboards this is handled for you. There may simply be a typo or you forgot to enter a reuse identifier for that cell.

Upvotes: 0

Related Questions