6 Replies
      Latest reply on Dec 31, 2017 12:27 PM by Claude31
      Adalex3 Level 1 Level 1 (0 points)

        I am trying to call a function that is located in a class "ViewController" from the AppDelegate. The function uses a few IBOutlets connected to a view controller such as "label.text", etc. When I call this function from the AppDelegate by making a reference to ViewController, then running "ViewController.function", the app crashes when it gets to the IBOutlets in the function. I'm guessing that this function is running from the AppDelegate, and that is why it can't find the IBOutlets. Is there any way to call the function from the AppDelegate, but have it run in the ViewController class? Thanks in advance, any help is appreciated.

        • Re: How to call a function in a class from the AppDelegate
          Claude31 Level 8 Level 8 (6,385 points)

          Are you sure the IBOutlets are instanciated when you call from AppDelegate ?

          Is the func in ViewController a class function or an instance function ?

           

          Another way is to post notification from AppDelegate and let the viewController handle it.

          • Re: How to call a function in a class from the AppDelegate
            QuinceyMorris Level 8 Level 8 (6,010 points)

            You need to be explict about what code you are using in your app delegate. This description is very vague:

             

            >> I am trying to call a function that is located in a class "ViewController"

             

            Is that a static function, or an instance function?

             

            >> When I call this function from the AppDelegate by making a reference to ViewController,

             

            What does "making a reference" mean? In most cases, the view controller instance (that has its outlets correctly set) already exists, and you need to find the reference to it.

             

            For example, if you have code like this in your app delegate:

             

                 let vc = ViewController ()
                 vc.function ()
            

             

            you will certainly crash, because this code creates a new ViewController object that does not have its outlets linked to anything (nor is it presented on the display, for that matter, which is another fatal problem).

             

            >> then running "ViewController.function

             

            Do you literally use this syntax:

             

                 ViewController.function ()
            

             

            or do you mean something else. This syntax almost certainly isn't what you want, unless you're calling a static function, in which case the reference to the view controller isn't needed or used.