Search code examples
iosswiftwatchkit

use performSegueWithIdentifier to get functionality of DestinationViewController, but not show it up


I have a WatchKit App that updates some labels with data from NSUserDefaults. These defaults are updated by two different ViewControllers in the iOS App. If I press a button in ViewController1, the view in the iOS App as well as the one in the WatchKit App gets updated (using NSTimer to update every second). So far so good, but now I need a defaults value to be shown on the Watch that is updated by iOS Apps ViewController2 only. I would like to stay on the view of ViewController1 but when I press the button, it should kind of 'run all the stuff' that is in ViewController2 (especially updating the specific NSUserDefault value after all the controllers math has been done) but without moving to it.

I have tried ViewController2().viewDidLoad() in the @IBAction function of the button in ViewController1, but this leads to a crash. Have also tried to use a Delegate like here and then to get my value from a hidden label, but could not make it work.

When I simply move to ViewController2 with self.performSegueWithIdentifier("moveToView2", sender: self) all works well (all lables on the Watch are updated), but I do not want to move to View2, I want to stay on View1 when the button is pressed but get the NSUserDefaults updated from View2 first...


Solution

  • You are fighting against bad design decisions.

    You need to rethink your design. If you have functionality that is tied to a view controller that you need elsewhere, you need to pull that functionality out into a non view controller class and call that.

    I often create a Utils class that I use. If the methods don't need state data, I'll make them class methods. If they need persistent state data, I make the utils class a singleton.

    I then call the methods I need inside the singleton.