0

I am trying to have two different xibs, and cells populated depending on "sender of messages". This determination seems to work fine, but when I try to set an attribute of the cell I am getting the following error:

fatal error: unexpectedly found nil while unwrapping an Optional value
2017-09-22 23:03:59.135734-0400 Phlare[67547:4037478] fatal error: unexpectedly found nil while unwrapping an Optional value

The error is in the else statement on the line:

cell.messageLabel.text = "Phlare"

This is the function where the error is occurring:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        //below is the creation of the nib variables
        let nib = UINib(nibName: "OutgoingUserMessage", bundle: nil)
        let nib2 = UINib(nibName: "IncomingUserMessage", bundle: nil)

        let msg = messageArray[indexPath.row]

        //below iterates through the array of sender ID's
        for i in 0...messageArray.count {
            print("for loop hitting")
            //the senderArray only holds an int if the user was the sender for that message

            //check to see if the sender is equal to the current user
            if(senderArray.contains(i)) {
                print("if statement hitting")
                let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! IncomingUserMessage
                //this means that the incoming message nib should be loaded
                self.myTableView.register(nib2, forCellReuseIdentifier: "cell")
                print("did not pick up sender")
                cell.messageLabel.text = "Phlare"
                return cell

            } else {
                print("the else loop is hitting")

                let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! OutgoingUserMessage
                //this meand that the outgoing message nib should be loaded
                self.myTableView.register(nib, forCellReuseIdentifier: "cell")
                print("picked up sender")
                cell.messageLabel.text = "Phlare"
                return cell
            }
        }
        return UITableViewCell()
    }

Does anyone know why this error may be occurring?

dgelinas21
  • 641
  • 3
  • 9
  • 22
  • Check your xib file, to make sure that the `message` outlet from your cell class is actually set. – Charles Srstka Sep 23 '17 at 03:12
  • Basically never register cells in `cellForRow` and basically never dequeue cells **before** registering them. And the repeat loop looks pretty strange, too. – vadian Sep 23 '17 at 03:15
  • 1
    I think the registration nib should be before cell de queue – Ram Sep 23 '17 at 03:18

0 Answers0