Search code examples
iosuistoryboarduistoryboardseguestate-restoration

iOS State preservation and restoration when data shared between view controllers


I'm implementing iOS state preservation and restoration for the first time, so this question may seem obvious to the more experienced!

I have a storyboard with multiple paths to various scenes. For example, from starting scene A the user can go to scene B and then scene C, or the user can go directly to scene C.

A "large" NSDictionary is created in View Controller A which is then passed to View Controller B and subsequently passed to View Controller C (or passed directly to C) via prepareForSegue methods.

I believe I'll be able to restore the NSDictionary in View Controller A, but how do I obtain it for View Controller B and/or C instead making additional copies?


Solution

  • Because the view controllers are restored in order, starting with the root, I found it's actually pretty simple to do what I asked. First, get the index of the current view controller in the Navigation controller. From that, figure out which view controller came before. (If my Storyboard was more complex, I could have used "isKindOfClass" on the previous view controller to determine how to get the NSDictionary in it.)

    For example:

    - (void)decodeRestorableStateWithCoder:(NSCoder *)coder
    {
        [super decodeRestorableStateWithCoder:coder];
    
        // get current index of views in navigation controller
        int index = [[self navigationController].viewControllers indexOfObject:self];
    
        if (index == 1) {
            ViewControllerA *view = [[self navigationController].viewControllers objectAtIndex:index - 1];
            self.dict = view.someDict;
        }
        else if (index == 2) {
            ViewControllerB *view = [[self navigationController].viewControllers objectAtIndex:index - 1];
            self.dict = view.arrayOfDict[0];
        }
    }