agf119105
agf119105

Reputation: 1810

Why am I getting EXC_BAD_INSTRUCTION error when I am trying to load my tableview in swift?

I am trying to populate my tableview after saving some values to my coredata database. I am asking it to display some of the values as indicated in my code, but whatever I do, I get the above error. Any suggestions? I have tried some of the other posts with this problem, but nothing seems to work.

I cannot think where I might be giving out a nil output Swift is not expecting.

override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {

    let CellId: NSString = "Cell"

    var cell: UITableViewCell = tableView?.dequeueReusableCellWithIdentifier(CellId) as UITableViewCell

    if let ip = indexPath {
        var data: NSManagedObject = myCustomers[ip.row] as NSManagedObject
        var addno = data.valueForKeyPath("custaddno") as String
        var addname = data.valueForKeyPath("custaddfirstline") as String
        cell.textLabel.text = "\(addno) \(addname)"
        var jcost = data.valueForKeyPath("custjobcost") as Float
        var jfq = data.valueForKeyPath("custjobfq") as Float
        var jfqtype = data.valueForKeyPath("custjobfqtype") as String
        cell.detailTextLabel.text = "Charge: \(jcost) to be done every \(jfq) \(jfqtype)"
    }
    return cell
}

Upvotes: 4

Views: 2046

Answers (2)

Medhi
Medhi

Reputation: 3225

Here a checklist to avoid this crash:

  1. Verify that your cell is registered to your table view
  2. Verify that your xib cell is marked with the correct identifier
  3. Verify that your xib is linked to the rights IBOutlets
  4. Verify that your IBOutlets are of the right types (ie UIView, UIImage, UIStackView, etc)

Upvotes: 0

Patrick
Patrick

Reputation: 167

Problem

You might have forgotten to register a class for the cell identifier before. See documentation of dequeueReusableCellWithIdentifier::

Discussion

Prior to dequeueing any cells, call this method or the registerNib:forCellReuseIdentifier: method to tell the table view how to create new cells. If a cell of the specified type is not currently in a reuse queue, the table view uses the provided information to create a new cell object automatically.

The method returns nil then and Swift fails to implicitly unwrap the optional.

Solution

In code

To solve this problem, you could either call registerClass:forCellReuseIdentifier: (see docs) in viewDidLoad like this...

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}

in Interface Builder

... or, if you're using Storyboards, set it directly in Interface Builder in the attributes inspector when the UITableViewCell prototype is selected:

Interface Builder

Upvotes: 2

Related Questions