How to exchange data between View Controllers

If you have two view controller classes you probably want to exchange data between them. Thanks to two methods we can do that, provided one view controller is presented via a modal segue. Here’s how it works step by step.

Imagine you had two labels on each View Controller. We’ll call them myLabel1 and myLabel2 (1is on ViewController, 2 on MyViewController). Both View Controllers need to be connected as described previously via a segue. You can access properties on ViewController from MyViewController like so:

self.myLabel1.text = ((MyViewController *)self.presentedViewController).myLabel2.text;

Likewise, if you’re in MyViewController you can access properties from ViewController like so:

self.myLabel2.text = ((ViewController *)self.presentingViewController).myLabel1.text;

Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or drawing on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.