Karagan App Karagan App - 2 months ago 9
iOS Question

Passing value over to next viewController

I am currently writing an app in

Swift
and I implemented all my UI programatically. I would it kind of exhausting, so recently I decided to use
storyboard
but I am stuck with a bug.

When passing over the
mainContext
from the
AppDelegate
to the
FirstViewController
, the value of the
mainContext
is
nil
. In the first place, when I wrote everything programmatically, my code looked like this:

let vc = FirstViewController()
vc.mainContext = mainContext
window?.rootViewController = vc


But now that I am working with
StoryBoard
, this is not valid anymore because I have to instantiate the view with its ID, like this:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
var vc = storyboard.instantiateViewControllerWithIdentifier("FirstView") as! FirstViewController
vc.mainContext = mainContext


But in this case, the context is
nil
. If I don't instantiate the VC like this, my outlets are
nil
and I get this error:

fatal error: unexpectedly found nil while unwrapping an Optional value


Does someone know a way to pass my
mainContext
?

Answer

You're not accessing the rootViewController, you're creating a new view controller and not doing anything with it, to access the rootViewController replace this

let storyboard = UIStoryboard(name: "Main", bundle: nil)
var vc = storyboard.instantiateViewControllerWithIdentifier("FirstView") as! FirstViewController
vc.mainContext = mainContext

with

if let vc = self.window?.rootViewController as? FirstViewController {
    vc.mainContext = mainContext
}