Xcode 6 Swift: Attempt to reset IBOutlets in AppDelegate

Using Xcode 6.0.1 w / Swift I created a shortcut in my storyboard and connected it to ViewController.swift resulting in:

@IBOutlet weak var myLabel: UILabel!

      

Whenever my application comes to the fore, I want to reset myLabel.text to use a specific string like "Hello World".

Earlier in Objective-C, I could do it in AppDelegate like this:

- (void)applicationWillEnterForeground:(UIApplication *)application {
self.viewController.myLabel.text=@"Hello World";
}

      

But I am struggling to get this to work in Xcode 6 in Swift. Since the AppDelegate didn't set up an instance of the view controller, I determined that in the AppDelegate:

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var vc: ViewController=ViewController()

      

Then tried the same approach:

func applicationWillEnterForeground(application: UIApplication) {
    vc.myLabel.text="Hello World"
}

      

But when I run the app the view renders well, then I hit home and then go back to the app and then I get a "fatal error: unexpectedly found null when expanding optional value"

So, I understand that UILabel is optional and I am getting this error because its value is zero. But I don't understand why its value is zero, since the view is already loaded. I tried using applicationDidBecomeActive with the same result. I cannot use viewDidLoad or viewWillAppear in my ViewController class because these methods are not called when the application moves from background to foreground state.

Also updated this to

    if vc.myLabel != nil {
        vc.myLabel.text="Hello World"
    }

      

and confident enough that the if statement is false.

Any ideas on how to reset UI elements in Xcode 6 and Swift? Thank.

+3


source to share


1 answer


Your problem is this line -

var vc: ViewController=ViewController()

      

allocates a new instance ViewController

. It does not provide a reference to the instance that is displayed on your storyboard, and since this instance is not initialized from the storyboard scene, so everything IBOutlet

is null.

I would suggest that you separate the application delegate and your view controller and take advantage of UIApplicationWillEnterForegroundNotification

.



Somewhere in your view controller initialization add

NSNotificationCenter.defaultCenter().addObserver(self, selector: "enterForeground", name:UIApplicationWillEnterForegroundNotification, object: nil)

      

and then declare a function to handle the event

func enterForeground {
   self.myLabel.text="Hello world"
}

      

0


source







All Articles