Question

I am currently developing a multi-view app with storyboards. In each view the user can enter data, generally through text boxes or button entry. This data is then stored in arrays.

My problem is this: when I transfer back to a window, viewDidLoad is called, and therefore resets all of the data. Is there a simple way (without simply loading my arrays back up) to retain this data, as if the viewDidLoad was not called? Is there a method that is called when the application is loaded, as opposed to just the view? Or perhaps a way to only call the viewDidLoad the first time?

I am aware I can solve this by loading my arrays back, I was just wondering if there's a simpler, more elegant solution.

EDIT:

It appears my view did load is triggering every time I go to another view. I am using storyboards segues.

Was it helpful?

Solution 4

From the comments I've gathered that the best way to do this is using an unwind segue. This can be done as follows:

Insert IBAction in segue I want to unwind to:

.h

- (IBAction)unwindToMain:(UIStoryboardSegue *)unwindSegue;

.m

- (IBAction)unwindToMain:(UIStoryboardSegue *)unwindSegue
{
    //Allows us to unwind back to this segue
}

Then simply ctrl dragging between the button in my second view controller and selecting the segue.

It is possible to find a good tutorial on this here:

What are Unwind segues for and how do you use them?

OTHER TIPS

You may use NSUserDefaults. in viewdidload check if you have data then load data or display default values. Every time a viewloaded viewDidLoad is called.

You can make the sub ViewControllers properties of the root, that way they won't be deallocated as you move between them. With the obvious caveat that when the app is killed data is lost.

For permanent storage of array data I suggest looking into NSCoding.

If anyone is interested in seeing how I solved this, I've used p-lists. It's quite a workaround, but the data is required to be in a p-list anyway, so this wasn't much of a stretch for my requirements:

First:

Ensure that the code that we want to run once at the beginning runs once:

 static dispatch_once_t once;
dispatch_once(&once, ^ { 
//all code we want to run once goes here
}

Secondly, when the view disappears write all required data into plist:

 (void) viewDidDisappear:(BOOL)animated
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFolder = [path objectAtIndex:0];
filePath = [documentFolder stringByAppendingFormat:@"wantedData.plist"];
[wantedDataArray writeToFile:filePath atomically:YES];
}

Finally, when view loads (or appears) fill an array with the contents of the p-list:

    retrievedDataArray = [NSArray arrayWithContentsOfFile:filePath];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top