antonyraja antonyraja - 1 year ago 102
iOS Question

How to access variables from one controller to another controller

Hi all am developing a app using swift 2.2 i declared a variable in first view controller i want to access that in second view controller.i have searched other stack overflow answers nothing supports me.

In my first view controller:

class firstViewController: UIViewController{

var timer:nstimer?
//performed some functions using nstimer

Now i want to stop the timer and i kept button action in the second view controller so i want to access the variable to access??

I searched before stack overflow answers that asked to use prepare for segue but am already given some connection and performed segue to other controllers.

Now am looking for the solution to access that variables.can anyone help me out from this problem??

Thanks in advance.

Answer Source

Your second ViewController shouldn't know anything about the first view controller, if it does then you essentially tie both VC's together.

What you need to do instead is either pass a reference through like @Sahil suggested above (although I would refrain from doing that as the first VC might not expect a change from an external source), or use a delegate pattern.

With a delegate pattern you give the second VC a weak reference to the first VC and have the first VC conform to a protocol defined by the second VC. The delegate pattern has been explained many times over so I'll just give you a link instead of explaining it again here:

The delegate pattern is the safest option and it allows the first VC to control the timer in an expected way rather than having it modified externally, so I would recommend exploring that option instead of passing a reference to the timer through.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download