Skip to content

Reset to a Factory Fresh Persistent Store

grgcombs edited this page Aug 4, 2011 · 1 revision

Reset to a Factory Fresh Persistent Store

Sometimes you might want to give your users the option of resetting the whole data store ... much like a "reset to factory settings", but for the data too. Granted, you'll probably want to put this in the separate Settings App, rather than leave it wide open for someone to shoot themselves in the foot, but you get the idea. Under pure Core Data, such a task is more of a burden. Thankfully, RestKit makes this dead-simple. In the code snippet below, I've included more than you actually need to do the job, but I wanted to show a little more detail on triggering a reset from a change in the application settings dictionary (NSUserDefaults).

- (BOOL) isDatabaseResetNeeded {
    [[NSUserDefaults standardUserDefaults] synchronize];
    BOOL needsReset = [[NSUserDefaults standardUserDefaults] boolForKey:kResetSavedDatabaseKey];
    
    if (needsReset) {
    
        [SLFAlertView showWithTitle:NSLocalizedStringFromTable(@"Settings: Reset Data to Factory?", @"AppAlerts", @"Confirmation to delete and reset the app's database.")
                            message:NSLocalizedStringFromTable(@"Are you sure you want to reset the legislative database?  NOTE: The application may quit after this reset.  New data will be downloaded automatically via the Internet during the next app launch.", @"AppAlerts",@"") 
                        cancelTitle:NSLocalizedStringFromTable(@"Cancel",@"StandardUI",@"Cancelling some activity")
                        cancelBlock:^(void)
                        {
                            [self doDataReset:NO];
                        }
                        otherTitle:NSLocalizedStringFromTable(@"Reset", @"StandardUI", @"Reset application settings to defaults")
                        otherBlock:^(void)
                        {
                            [self doDataReset:YES];
                        }];
    }
    return needsReset;
}

- (void)doDataReset:(BOOL)doReset {
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kResetSavedDatabaseKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if (doReset) {
        [self resetSavedDatabase:nil]; 
    }
}

- (void) resetSavedDatabase:(id)sender {
    RKManagedObjectStore *objectStore = [[RKObjectManager sharedManager] objectStore];
    [objectStore deletePersistantStore];
    [objectStore save];    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DATA_STORE_RELOAD" object:nil];

}