LK Phuc Nguyen LK Phuc Nguyen - 6 months ago 10
Swift Question

Swift - Reference viewControllers in navigationController by index number

This code illustrates what I am asking:

For a simple app having 2 screens, the

rootViewController
and a
TableViewController
, the
rootVC
will be at index [0] in
navigationController
, the next views will increments the index by 1

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

let navController = self.window?.rootViewController as! UINavigationController
let firstViewController = navController.viewControllers[0] as! firstViewController
firstViewController.managedObjectContext = self.managedObjectContext

return true
}


Now I am trying to pass
managedObjectContext
from
appDelegate
to the ViewControllers behind the
rootViewController
:

The center view is
rootViewController
, I want to pass
managedObjectContext
to the screens next, above and below it.

I have tried passing it from
appDelegate
to
rootViewController
, then passing from
rootViewController
to the next views but it does not work.

Anyone please tell me how to know the index numbers of the views following the same view? Thank you!

Answer

Now I am trying to pass managedObjectContext from appDelegate to the ViewControllers behind the rootViewController

You can't. The entire idea makes no sense. At the time the code in the app delegate runs, those view controllers do not exist yet. A storyboard is merely a set of instructions for making future instances of view controllers; there are no such instances during application:didFinishLaunchingWithOptions: — except for the first one that you make, explicitly, right there in your code.

Instead, each of those view controllers needs to fetch the managedObjectContext from the app delegate, in their own code (such as their viewDidLoad). That is something they can all easily do, because the app delegate has a managedObjectContext property, and they can all see that property because they can all see the app delegate (because it is the shared application's delegate).

Comments