Last Updated: February 25, 2016
·
752
· parrots

Prevent state restoration on version upgrade

You always want to check which version of your app previously saved the state using iOS6's state saving and restoration, as screens/data/etc can change from version to version.

Instead of having conditional logic in the decode methods on your view controller, just add this to your AppDelegate to prevent restoration all together when the user just upgraded the app. This code uses the version number in your app's bundle.

#define kStateSavingPreviousVersion @"PreviousAppVersionNumber"
#define kVersionNumber @"CFBundleShortVersionString"

-(BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder
{
    //we don't want to restore if the state is from a previous app
    NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:kVersionNumber];
    NSString *previousAppVersion = [coder decodeObjectForKey:kStateSavingPreviousVersion];
    return [previousAppVersion isEqualToString:appVersion];
}

-(BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder
{
    NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:kVersionNumber];
    [coder encodeObject:appVersion forKey:kStateSavingPreviousVersion];

    return YES;
}