Core Data and Relationship (Unexpectedly found nil...)

Hello,

I need help with “Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value”

I have this NavigationController on my Storyboard:
RoomTableViewController (with all my items:room-entity) goes to → DetailViewController with details of the row from room-entity and a separate DayTableView inside to select → one day at the WeekTableViewController as a relationship.

In detail:
I have an item (room) and I want to assign a (day) - I worked with the BowTie and Device Relationship video-example. If I add and save my new item (room) go back to the RoomTableViewController, than select the row and want to assign in this second step the “day” everything is OK and worked for me.

But I want to do all in one step :wink:
→ Add the new room and assign the day from the DayTableViewController.

At this point I earn the “ERROR” = myRoom.weekday_rls = wochentag If I want to do it in one step it is nil, I I do the same in the two steps I can save the room and assign the day crazy

extension AddRoomViewController : DayPickerDelegate {
func didSelectDay (wochentag: Wochentag){
    do {
        myRoom.weekday_rls = wochentag
        try fetchedResultsCtrl.managedObjectContext.save()

        print("Picker gespeichert")
        print(wochentag)
    } catch {
        print("Error saving todo: \(error)")
    }
}

}

Some more code from my project:

lazy var appDelegate = UIApplication.shared.delegate as! AppDelegate
var managedContext = (UIApplication.shared.delegate as! AppDelegate).managedContext

var myRoom: Raumliste!
            
lazy var fetchedResultsCtrl: NSFetchedResultsController<Raumliste> = {
        let request: NSFetchRequest<Raumliste> = Raumliste.fetchRequest()
        let sort = NSSortDescriptor(key: "name", ascending: true)
        request.sortDescriptors = [sort]
        let fetchedCtrl = NSFetchedResultsController(fetchRequest: request, managedObjectContext: self.managedContext, sectionNameKeyPath: nil, cacheName: nil)

        fetchedCtrl.delegate = self
        return fetchedCtrl
    }()



func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
saveDataBase()
        if indexPath.section == 1 && indexPath.row == 0{
            if let weekDayPicker =
                storyboard?.instantiateViewController(withIdentifier: dayCell) as? WochentagController {

     weekDayPicker.managedContext = self.fetchedResultsCtrl.managedObjectContext

        //Week Setup
        weekDayPicker.dayPickerDelegate = self
        weekDayPicker.selectedDay = myRoom?.weekday_rls
        


        navigationController?.pushViewController(weekDayPicker, animated: true)

        }
    }
    tableView.deselectRow(at: indexPath, animated: true)
}

Why I got the crash? Why Ii is nil?

From the details in your post and guessing at other details, I was able to put this playground example together:

import UIKit

class MyViewController {
    var myRoom: Room!
}

class Room {
    var weeday_rls: Wochentag!
}

enum Wochentag {
    case Montag
    case Dienstag
    case Mittwoch
    case Donnerstag
    case Freitag
    case Samstag
    case Sonntag
}

protocol DayPickerDelegate {
    func didSelectDay(wochentag: Wochentag)
}

extension MyViewController: DayPickerDelegate {
    func didSelectDay(wochentag: Wochentag) {
        myRoom.weeday_rls = wochentag   //<--------<-----+ found nil while unwrapping optional
    }                                          //        |
}                                              //        |
                                               //        ^
let mvc = MyViewController()                   //        |
mvc.didSelectDay(wochentag: Wochentag.Montag)  //Error --+

Room has a property declared as an implicitly unwrapped optional, and implicitly unwrapped optionals are automatically initialized with nil–that’s why you don’t need to define an init() method. If every property in your class does not have a default value, then you do have to define an init() method in your class. Most beginning iOS tutorials make sure that all the properties in a class have default values so that that the tutorials don’t have to explain the concept of the init() method. In the case of @IBOutlet properties, which are declared as implicitly unwrapped optionals, iOS makes sure to assign the controls to the properties shortly after an instance of your ViewController class is created, and by the time your code can interact with a control, the property can’t be nil. .

@7stud

ok, if I understand you in the right way… I need a default value at the same time saveing the new room. so every room get “Monday” as default, right?

But how can I set a default value for a relationship?
myRoom.weekday_rls = 1 // this is not posible :slight_smile: (Cannot assign value of type ‘Int’ to type 'Wochentag)

This topic was automatically closed after 166 days. New replies are no longer allowed.