Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 794
agf119105 Avatar asked Oct 31 '22 21:10

agf119105


1 Answers

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

like image 93
Patrick Avatar answered Jan 04 '23 15:01

Patrick