1
votes

I'm trying to populate a label in my custom cell for my UITableViewController with information from my Firebase Database but I keep running into this error:

"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

I did read this link: What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?

I don't think I'm accessing outlets before they're loaded in and I did check that my IBOutlet connection is correct.

class FeedCell: UITableViewCell {

    @IBOutlet weak var postText: UILabel!

}

class FeedTableViewController: UITableViewController {

    var postInfo = FeedCell()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//         self.navigationItem.rightBarButtonItem = self.editButtonItem

        self.tableView.rowHeight = 100.0

//        postText = UILabel()
//
        var ref: DatabaseReference!
        ref = Database.database().reference()
        let cellRef = ref.child("post/body")

        cellRef.observeSingleEvent(of: .value) { (snapshot) in
            if let body = snapshot.value as? String {
                self.postInfo.postText.text = body
                print(body)
            }
        }
    }

Here's my database

I expected the label to be updated with the body text "test firebase" but I'm just running into that error. Is it because I defined my IBOutlet in another class then referenced it in my FeedTableVIewController? Any advice would be appreciated!

1
at first you should never access outlets directly, second create a model for the data, in the if statement populate array of type model with the data you would get from firebase and then in cellForRowAtIndexPath method you configure cell with the dataLatenec

1 Answers

1
votes

The problem is here

var postInfo = FeedCell()

with

self.postInfo.postText.text = body <<< postText is nil

First you shouldn't create an instance var of a cell , and as your current var here postInfo is initated with FeedCell() so the outlet is nil regardless of it's connected / not

Second you should make use of table delegate and dataSource methods to populate your table