Search code examples
iosiphonesqliteresetnsfilemanager

Reset sqlite db to default values


I am writing a reset function within my app which will restore my sqlite database to its original state with some pre-populated data. The code below removes the database from the documents directory and copies over the database from the bundle yet the data still appears from the old database?

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"MoneyMonthly.sqlite"];

 if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){ 

    [[NSFileManager defaultManager]      removeItemAtPath:filePath error:nil]; 

}

BOOL success; 
NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *error;

NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"MoneyMonthly.sqlite"]; 
 NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"MoneyMonthly.sqlite"]; 

 success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 

if (!success) {

    NSAssert1(0, @"Failed to create writable   database file with message '%@'.", [error localizedDescription]); 
}

Solution

  • I do this in one of my apps. I keep a pre-built database file in my app's bundle. This database has all of the tables and sample data.

    When I need to reset the user's database, I shut it down, then overwrite the database with the clean copy from the bundle.