0

I am wondering if there is a way to maintain user input when navigating back and forth to my main menu using the UINavigationBar back arrow using NSCoder. I am currently using NSCoder to maintain this data during background/terminate/restart and NSUserDefaults to maintain data between views, but the combination of NSCoder and NSUserDefaults is giving unpredictable results. Sometimes, both types of restoration work, but sometimes the BG/Term/RS restoration does not work, and I am talking about loading the same identical code on my device. When the NSUserDefaults code is commented out, the BG/Term/RS restoration works every time.

I would like to know if it is possible to use NSCoder for all of my restoration needs, and if so, what that code would look like.

This is what I am using for BG/Term/RS restoration:

-(void)encodeRestorableStateWithCoder:(NSCoder *)coder {
    // start level text
    [coder encodeObject:_startLevel.text forKey:@"startText"];

    // stop level text
    [coder encodeObject:_stopLevel.text forKey:@"stopText"];
}

-(void)decodeRestorableStateWithCoder:(NSCoder *)coder {
    // start level text
    _startLevel.text = [coder decodeObjectForKey:@"startText"];

    // stop level text
    _stopLevel.text = [coder decodeObjectForKey:@"stopText"];
}

This is the NSUserDefaults code that I am currently using to persist data back and forth between my menu and main view, and which I would ideally like to replace with an NSCoder solution:

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    // start level
    [[NSUserDefaults standardUserDefaults] setObject:_startLevel.text 
                                              forKey:@"startLevelRestore"];
    // stop level
    [[NSUserDefaults standardUserDefaults] setObject:_stopLevel.text 
                                              forKey:@"stopLevelRestore"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];

        // start level
        [_startLevel setText:[[NSUserDefaults standardUserDefaults]
                                     objectForKey:@"startLevelRestore"]];

        // stop Level
        [_stopLevel setText:[[NSUserDefaults standardUserDefaults] 
                                     objectForKey:@"stopLevelRestore"]];

        [[NSUserDefaults standardUserDefaults] synchronize];    
    }

I have been battling this issue for a couple of days with no luck. Any help would be greatly appreciated! Thanks.

Alex Cio
  • 6,014
  • 5
  • 44
  • 74
C_Dub
  • 77
  • 11

1 Answers1

0

Instead of setting UI objects in decodeRestorableStateWithCoder: use a member variable.

Then in viewWillAppear: use the member variable if it has been set otherwise use the value from NSUserDefault.

Carl
  • 2,896
  • 2
  • 32
  • 50