I’ve been restructuring my 1st Core Data App to use the approach from the book. I have created the CoreDataStack.swift, updated my AppDelegate… And my MasterViewController
(the master view controller shows me a list of all the records in CoreData - which at the time is empty).
I have an Add button via a Prepare for Seque
The program crashes at the Recipient(context: managedContext), with the message:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
The “nil” it is finding, is in the coreDataStack
I’ve been scratching my head most of this weekend. Any suggestions how to figure this out? I have confirmed that it is nil during the prepare for segue.
but since the database has no value in it… should the Add button create the context?
If I remove the if let context = coreDataStack { } wrap around the if let coreDataCards = try? then I actually get a crash a the if let coreDataCards = try? - with:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
OK… Figured out what I was missing, I was not passing the managedContext between view controllers. Should I be passing it or should I declare it as a global variable?
The approach in the core data book is to create coreDataStack in the app delegate, pass it to the root or master view controller, and have it pass it along to any other view controllers. Your first post seems to show that happening with the addVC controller.
Then each controller uses coreDataStack.managedContext anywhere it needs to get to the managed context. You don’t use a separate managedContext variable.
So in that first post, for instance, you would create the new recipient with
@theapapp You definitely pass it between View Controllers and should avoid using a global variable (i.e. via a Singleton). Also remember that you should pass it between View Controllers even if the immediate View Controller is NOT in need of it. For example:
Your app has 3 View Controllers, let’s call them A, B, C. If A uses the MOC, B does not, and C does. What do you do? How do you get the same reference of the MOC over to C from A? Simple, A gives it to B, which gives it to C. Even though B is not using it, you should still pass it to B, so that it can send it to C where it will be used.