How to Retain UIDatePicker and UITextField Values When Switching View Controllers?

353 Views Asked by At

I have two View Controllers. View Controller #2 has a UIDatePicker and a UITextField.

If I go back to View Controller #1 then back to View Controller #2, the UIDatePicker has lost its previous selected date and the UITextField is blank.

It was initialized this way:

@property (retain, nonatomic) IBOutlet UIDatePicker *datepick;

I am getting to the 2nd View Controller using a Push Segue and getting back using:

[self.navigationController popViewControllerAnimated:YES];

How can I 'SAVE' the UIDatePicker date and UITextField value so that it is always there when returning to that View Controller?

I have searched and found opinions, hypotheticals, and suggestions but no solutions.

Thank you.

1

There are 1 best solutions below

3
On

This happens, because (if you manage memory properly) the second view controller is released when you pop it (go back to the first one). So when you want to go back to it, you actually create a completely new instance, with default values.

One solution would be to make sure you have a strong reference to view controller 2, from view controller 1. Add a property in the first view controller:

@property (nonatomic, retain) SecondViewController *mySecondViewController;

Implement the getter:

- (SecondViewController *)mySecondViewController {
    if (!mySecondViewController) {
        mySecondVieWController = [[SecondViewController alloc] init...];
    }
    return mySecondViewController;
}

Then when you want to present it:

[self.navigationController pushViewController:self.mySecondViewController animated:YES];

The first time you call it, mySecondViewController will still be nil, so the getter initializes it. The next time you call the getter, it simply returns the same instance.

Don't forget to release the view controller in dealloc. And by the way, consider using Automatic Reference Counting (ARC).

This approach is relatively easy to implement, but it has to downside, that the second view controller is kept in memory, even when it's not needed anymore.

An other way would be to pass back the selected date or text to your first view controller (possibly via a custom delegate protocol) and the next time you want to present the second view controller, you pass it these values to set the date and text.