1

I've an app that keep four variables in the first view controller. The second view controller, pushed through navigation controller, should send these variables to a web form.

So I need these four vars in the second view controller.

At the moment, in the 1st view controller I set the vars in the app delegate with:

MyDelegate *delegate = (MyDelegate *) [[UIApplication sharedApplication] delegate];
delegate.var1 = var1;
delegate.var2 = var2;
[...]

And when I need them in the second view controller, I'll get them through my delegate. But probably, this is the wrong way.

How can I transfer my vars between the controllers? What's the best way?

Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
Joaquin McCoy
  • 425
  • 2
  • 7
  • 16
  • This is a good resource from a different answer: http://stackoverflow.com/questions/569940/whats-the-best-way-to-communicate-between-view-controllers – iwasrobbed Feb 23 '11 at 17:55

3 Answers3

4

Declare properties for these variables in the second view controller and then, when you create the second view controller and before you push it to the navigation stack, assign values to those properties.

Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
  • I agree entirely. They're parameters passed from the first controller to the second. There's no sense in making them global state and hence no good practice way of doing so to recommend. – Tommy Feb 23 '11 at 17:54
  • 1
    I know Tommy. Thank you for your suggest. A question, is a bad way passing them through a constructor? – Joaquin McCoy Feb 23 '11 at 17:56
  • how can I do the reverse action? I mean change variables of the first view controller when I am in the second view controller. One way is use NSUserDefaults, but also this is not the good way, probably. – Joaquin McCoy Feb 23 '11 at 18:10
  • User defaults is not the worst way IMO, assuming this is regarding data that ends up in the user defaults anyway (in that case, the user defaults act as the model). Other possibilities: VC2 saves the model data and other controllers get notified about this change in the model (either by observing model changes or by receiving a notification from the model). Or you implement a delegate protocol in VC2 and make VC1 the delegate of VC2. – Ole Begemann Feb 23 '11 at 19:17
0

As long as the variables are declared as instance variables in the header the should be reachable as long as the UIView Controller is still instantiated.

0

I think the best practice is to pass it through MySecondViewController constructor.