0

I have set the ViewController() as a sharedInstance. When I try to fire a function from another view the shared function returns

fatal error: unexpectedly found nil while unwrapping an Optional value

I dont understand why is giving me an error using a sharedInstance and it works good if I call the function from inside the `ViewController'

class ViewController: UIViewController {

static let sharedInstance = ViewController()

@IBOutlet weak var playBtn: UIButton!

///

///

func audioPlayerIsNotPlaying() {

        print("stop") //runs

        playBtn.selected = false //fatal error: nil
        playBtn.setImage(UIImage(named: "playBtn.png"), forState: UIControlState.Normal ) //fatal error: nil

    }

}

Second View Controller:

ViewController.sharedInstance.audioPlayerIsNotPlaying()

Why is the playBtn button object is returning nil?

0

2 Answers 2

2

A view created programmatically will not have outlets set. You need to create the instance from a nib or storyboard.

Sign up to request clarification or add additional context in comments.

1 Comment

however, if I call the function from the second view using postNotificationName the function is called
1

In order for the view controller's outlets to be hooked up, you have to instantiate it through the storyboard (or NIB). For example, if you're going to try to have a static reference to a view controller, you would do something like:

static let sharedInstance = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("identifier")

Otherwise the outlets will be nil.

11 Comments

I have tried using your method however, I still have the fatal error on the button
also in order to work I had to add as! ViewController at the end
@SNos - Yep, if you needed it as a ViewController rather than just a UIViewController, then obviously cast it as appropriate. There was nothing in your question suggesting you needed it as a ViewController, but if you do, then cast it.
Rob, I'm doing the exact same thing as you mention, and my outlets are nil. I'm running in on iPhone 6, ios 9.3. Am i doing something wrong? static let sharedInstance = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("IAP") as! newIAPClass
There's nothing in the sharedInstance pattern that prevents you from calling methods of another class (though you'll obviously want to cast it to the right class associated with the base class for that scene). There must be something else going on. But we're deviating sufficiently from the topic at hand that I'd encourage you to post your own question if you have one, and we discontinue these comments (perhaps even deleting some of them).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.