简体   繁体   中英

iOS 5 - Coredata Sqlite DB losing data after killing app

I'm using coredata with a sqlite DB to persist data in my app. However, each time I kill my app I lose any data that was saved in the DB. I'm pretty sure its because the .sqlite file for my DB is just being replaced by a fresh one each time my app starts, but I can't seem to find any code that will just use the existing one thats there. It would be great if anyone could point me towards some code that could handle this for me.

Cheers

B

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
    return __persistentStoreCoordinator;
}

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber     numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];    
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"FlickrCoreData.sqlite"];

NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
{
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}    

return __persistentStoreCoordinator;
}

Changes to a managed object context in core data are not saved at the time you make the changes for optimization purposes. This way you can make a bunch of changes to your context and then persist all the changes at once. So if you are killing your app before it has a chance to autosave you will then lose all your data. I'm guessing this is what you are experiencing here.

In any case, try explicitly making a call to save your data before closing your app. This should solve your problem.

For example, assuming you have a variable that holds your managed object context called context you can save your context by making the following call somewhere in your code before closing the app:

[context save:&error] or simply [context save:nil]

Have you tried place [self saveContext] in appDelegate function applicationWillTerminate: . You should save the context before terminate the application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM