0

I am trying to access the objects from child controller but it always returns nil. Please check the below code.

let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc: UITabBarController = mainStoryboard.instantiateViewController(withIdentifier: "TabBarController") as! UITabBarController
vc.selectedIndex = 2
let vc1 = vc.viewControllers?[2] as? FormViewController //this line returns nil
vc1?.fillUserData(dataDic: convertJsonStringToDictionary(jsonString: decodedURL))
vc1?.formViewDelegate = self
self.present(vc, animated: true, completion: nil)

Please shed some light.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Mac_Play
  • 302
  • 4
  • 21
  • It's probably nil because the 3rd view controller isn't a `FormViewController`. Maybe it's a navigation controller. – rmaddy Sep 09 '18 at 21:30
  • Am sure third view Controller is formviewcontroller and it's embed in navigation controller. – Mac_Play Sep 09 '18 at 21:31
  • That's my whole point. `vc.viewControllers?[2]` is *not* a `FormViewController`, it's a `UINavigationController`. That is why you get `nil`. – rmaddy Sep 09 '18 at 21:32

2 Answers2

2

Based on your comments, the 3rd tab is actually a UINavigationController which has the FormViewController as its rootViewController.

Update your code as:

if let nc = vc.viewControllers?[2] as? UINavigationController, let vc1 = nc.topViewController as? FormViewController {
    vc1.fillUserData(dataDic: convertJsonStringToDictionary(jsonString: decodedURL))
    vc1.formViewDelegate = self
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
1

You can try

let nav = vc.viewControllers?[2] as? UINavigationController
let vc1 = nav?.topViewController as? FormViewController

note : you should not access any UI element here

vc1?.fillUserData(dataDic: convertJsonStringToDictionary(jsonString: decodedURL))

as it would crash the app

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87