Roi Mulia Roi Mulia - 7 months ago 74
Swift Question

Loading UIViewController from instantiateViewControllerWithIdentifier - nil outlets

I honestly can't understand what am i doing wrong.

I have this shared Instance of my UIViewController :

static let sharedInstance = UIStoryboard(name:"Main", bundle:nil).instantiateViewControllerWithIdentifier("IAPNEW") as! newIAPClass


If i'm presenting it, without accessing it outlets, as so :

self.presentViewController(newIAPClass.sharedInstance, animated: true, completion: nil)


It's works as expected(show's up). BUT - if i'm trying to access his outlets, it's crashing with "found nil" error :

newIAPClass.sharedInstance.lbl_full.text = "mMM"
self.presentViewController(newIAPClass.sharedInstance, animated: true, completion: nil)


Someone,Any idea why the outlets are nil?

Answer

The outlets aren't set up initially. The standard way to deal with this is to store your data in properties and then move that data into your outlets in viewDidLoad.

Since you are loading this in a Singleton, viewDidLoad will only be called once. Instead, copy your data from your properties to your outlets in viewWillAppear.