Isaiah Turner
Isaiah Turner

Reputation: 2662

How can I use a variable in two modal separated view's with the same class (.h and .m files)?

I am trying to use a variable (birthDateLabel) in two view controllers that are separated via a modal but use the same view controller class (CreateAccountViewController). The label works in the view that it is set in but after [self dismissViewControllerAnimated:YES completion:nil]; is run the varriable is reset, how can I retain it?

Order of operations:

  1. The first instance of CreateAccountViewController is run
  2. A button is tapped to go to a new instance of CreateAccountViewController but this instance has a different view with a UIDatePicker to set the birthDateLabel variable.
  3. The birthDateLabel is set
  4. The user taps done and dismissViewControllerAnimated is run
  5. The app updates a UILabel on the first instance of CreateAccountViewController

Step 5 is what does not work, if I put the label on the view as the picker it works but when the modal is dismissed the variable is reset. How can I keep the variable set after the modal is dismissed? Or is my only option to create separate view controller classes?

I tried to do my best explaining this, but if you need me to explain it more just comment.

Upvotes: 0

Views: 57

Answers (2)

Ben Coffman
Ben Coffman

Reputation: 1740

@rdelmar provides the most technically correct answer, but if it's just one value you could simply use nsuserdefaults. If the number begins to expand creating a delegate might be a smart choice.

Upvotes: 1

rdelmar
rdelmar

Reputation: 104082

The standard way to do this is to use a delegate. The fact that your two controllers are both instances of the same class doesn't make any difference, other than they will both have a variable called birthDataLabel. The value of that variable is specific to each instance, just as it would be if these were of two different classes.

So, you should do it the right way, which is to create a delegate protocol in your second instance, and have the first one set itself as the delegate when it first presents the second one.

Upvotes: 2

Related Questions