mihai mimi
mihai mimi

Reputation: 133

Prepare for segue lead to "found nil while unwrapping an Optional value"

Im attempting to perform a segue from a table view cell that has one value "the floor number" to another vc which will be used to assign the number of rooms per floor. I have break points throughout the function to verify is the value that is passed is nil. The point is that it is not nil and it has the value "floor number". When i attempt to assign that value to a variable in the next VC i get the unwrapping optional found nil error. Could someone please help me out with this one as I don't see where this is coming from is the debugger shows me that I have a value inside the variable i want to pass. Code listing below. Thank you:

class AssignNumberOfRoomsForFloorsVC: UITableViewController {

//MARK: - Properties

private var managedObjectContext: NSManagedObjectContext!

private var storedFloors = [Floors]()


//MARK: - Actions

override func viewDidLoad() {
    super.viewDidLoad()
    managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    loadFloorData()
    self.tableView.reloadData()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

private func loadFloorData() {
    let request: NSFetchRequest<Floors> = Floors.fetchRequest()
    request.returnsObjectsAsFaults = false
    do {
        storedFloors = try managedObjectContext.fetch(request)
    }
    catch {
        print("could not load data from core \(error.localizedDescription)")
    }
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return storedFloors.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "floor cell", for: indexPath) as! FloorCell
    let floorItem = storedFloors[indexPath.row]
    cell.floorNumberTxt.text = String(floorItem.floorNumber)
    return cell
}

// MARK: - Navigation

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    var selectedRow = self.tableView.indexPathForSelectedRow
    let floorItem = storedFloors[(selectedRow?.row)!]
    let destinationController = segue.destination
    if let assignRoomsVC = destinationController as? DeclareRoomsVC {
        if let identifier = segue.identifier {
            switch identifier {
            case "assign number of rooms":
                assignRoomsVC.floorNumberTxt.text = String(floorItem.floorNumber) // ERROR HAPPENS ON THIS LINE
                assignRoomsVC.selectedFloor = floorItem.floorNumber

            default: break
            }
        }
    }
}

}

Upvotes: 0

Views: 206

Answers (1)

Taylor M
Taylor M

Reputation: 1865

In the prepare for segue method, the view hasn't loaded yet and thus your storyboard hasn't created any of your views.

It looks like floorNumberTxt is probably a text field or a label. You're trying to assign a property of this view, but that view doesn't exist yet. Thus the "found nil while unwrapping an Optional value” error message.

Try adding let _ = assignRoomsVC.view before assigning any of the view controller's view properties. By accessing the view (assignRoomsVC.view), you'll force the view load and instantiate all its subviews.

Upvotes: 3

Related Questions