[英]iOS 5 - Coredata Sqlite DB losing data after killing app
I'm using coredata with a sqlite DB to persist data in my app. 我将coredata与sqlite DB结合使用以将数据持久保存在我的应用程序中。 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.
我非常确定,因为每次我的应用启动时,数据库的.sqlite文件都会被替换为一个新的.sqlite文件,但是我似乎找不到任何将使用现有代码的代码。 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
,则可以通过在关闭应用程序之前在代码中的某个位置进行以下调用来保存上下文:
[context save:&error]
or simply [context save:nil]
[context save:&error]
或只是[context save:nil]
Have you tried place [self saveContext]
in appDelegate function applicationWillTerminate:
. 您是否尝试将
[self saveContext]
放置在[self saveContext]
函数applicationWillTerminate:
。 You should save the context before terminate the application. 您应该在终止应用程序之前保存上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.