User cell: fatal error: null unexpectedly found while deploying optional value

I have a table view with a custom cell that was created as .xib. I did not use the storyboard. I have a problem that I could not populate my table with data obtained from the webservice result. In addition, I have 4 tags in a user cell. In my cell class, when I try to set labels for each element, it gives me a fatal error, as shown above.

Here is my code:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { ... func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell: ItemManagementTVCell = tableView?.dequeueReusableCellWithIdentifier("cell") as ItemManagementTVCell if let ip = indexPath { let item: Item = self.itemList[indexPath.row] as Item cell.setCell(item.itemName, status: item.itemStatus, duration: item.itemDuration, price: item.itemPrice) } return cell } } 

And my custom cell class is here:

import UIKit

 class ItemManagementTVCell: UITableViewCell { @IBOutlet var lblItemName: UILabel! @IBOutlet var lblItemPrice: UILabel! @IBOutlet var lblItemDuration: UILabel! @IBOutlet var lblItemStatus: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func setCell(name: String, status: Int, duration: Int, price: Int) { self.lblItemName.text = name self.lblItemStatus.text = String(status) self.lblItemDuration.text = "Duration: \(String(duration)) months" self.lblItemPrice.text = String(price) + " $" } } 

I get an error inside the setCell method block.

I read a lot of questions and solutions, and I tried them all, that it does not work for me.

Thank you for your responses,

Sincerely.

SOLUTION: I solved this problem by linking the cell elements to my own cells instead of referring to the File Owner. My problem went away by doing this.

+6
source share
2 answers

Your "cell" must be zero.

Using

 tableView.dequeueReusableCellWithIdentifier("cell") as ItemManagementTVCell 

May return zero. You should use:

 tableView.dequeueReusableCellWithIdentifier("cell" forIndexPath:indexPath) as ItemManagementTVCell 

Thus, it ensures that the cells are not zero.

EDIT: Perhaps you can prevent the failure by setting if statements inside "setCell"

 if var itemName = self.lblItemName { itemName.text = name } 

Do this for each marking installed inside it and check if a malfunction has occurred. If this is not the case, you should check why these labels are zero.

+7
source

Another solution to the problem without binding cell elements to the cell owner:

 let nib = UINib(nibName: "YOUR_CUSTOM_CELL_NIB_NAME", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "YOUR_CUSTOM_CELL_ID") 
+4
source

Source: https://habr.com/ru/post/974550/


All Articles