1

I am creating a calculator app in which I need to set a variable in a separate view controller from a settings page. When attempting this feat some weird things happen. First, it somehow the variable returns nil. Then, it initialized a new view controller. Yet, all the non-static variables are the same when I reopen an instance of the old view controller.

There might be an error in my code:

func updateTag(title: String){
    switch(title){
    case "displayWithPrecisionSwitch":
        let mainViewController = storyboard?.instantiateViewController(withIdentifier: "timerViewController") as! ViewController
        mainViewController.updatePercision()
        mainViewController.correctTallyDisplay?.refresh(totalTime: mainViewController.counter.getIntegerTime(), goal: mainViewController.counter.getGoal())
        mainViewController.incorrectTallyDisplay?.refresh(totalTime: mainViewController.counter.getIntegerTime(), goal: mainViewController.counter.getGoal())
        print(mainViewController.correctTallyDisplay?.percision ?? "Warning Nil")
    default:
        print("break")
        break;
    }
}

Or in the UI: enter image description here enter image description here I just need to find a way to call functions from "timerViewController".

1 Answers1

0

Yes you are initializing a new view controller when you callstoryboard?.instantiateViewController and you should not be doing that. To simply call a method in another view controller, you can use NSNotificationCenter like this, or create a delegate to achieve the same result. The first one is easier to implement.

Here is an example if you just need to call a method from another view controller. Lets say your caller view controller is trying to call a method in your callee controller.

So in your callee controller, you need to resister to receive this type of call in your viewDidLoad method. So put this code there to do the registration

NotificationCenter.default.addObserver(self, selector: #selector(methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)

Then you need the method that this notification is calling

func methodOfReceivedNotification(notification: Notification){
    //either replace the function name to your function or call your function here
}

Then in your caller view controller which is setting view controller or any other view controller, when you want to call this registered method, simply do

NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)
Fangming
  • 24,551
  • 6
  • 100
  • 90