【问题标题】:iOS 5 - Coredata Sqlite DB losing data after killing appiOS 5 - Coredata Sqlite DB 在杀死应用程序后丢失数据
【发布时间】:2012-03-18 17:58:18
【问题描述】:

我正在使用 coredata 和 sqlite DB 来将数据持久保存在我的应用程序中。但是,每次我杀死我的应用程序时,我都会丢失保存在数据库中的所有数据。我很确定这是因为每次我的应用程序启动时,我的数据库的 .sqlite 文件都会被一个新文件替换,但我似乎找不到任何只使用现有文件的代码。 如果有人能指出一些可以为我处理这个问题的代码,那就太好了。

干杯

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;
}

【问题讨论】:

  • 每次写入存储时都必须使用相同的 ManagedObjectContext。您如何将数据写入 moc 以及如何将 ManagedObjectContext 传递给其他控制器。

标签: iphone ios sqlite core-data


【解决方案1】:

在您进行更改以进行优化时,不会保存对核心数据中托管对象上下文的更改。这样,您可以对上下文进行大量更改,然后一次保留所有更改。因此,如果您在应用程序有机会自动保存之前将其杀死,您将丢失所有数据。我猜这就是你在这里所经历的。

在任何情况下,请尝试在关闭应用之前明确调用以保存您的数据。这应该可以解决您的问题。

例如,假设您有一个名为 context 的变量保存您的托管对象上下文,您可以通过在关闭应用程序之前在代码中的某处进行以下调用来保存您的上下文:

[context save:&error] 或简单的[context save:nil]

【讨论】:

  • 嗨,Jake,我的 AppDelegate 确实从 applicationDidTerminate 方法调用了上下文的保存。这是你的意思吗?
  • 是的 - 不想告诉您将保存调用的确切位置,因为这取决于最适合您的程序结构的内容。但是,我想说把它放在“Will...”委托方法之一中,即applicationWillTerminate - 这样您就可以给程序一点时间来实际进行保存。
  • 谢谢。我实际上不得不从“applicationDidEnterBackground”调用“[context save:&error]”。根据文档“如果您的应用程序支持后台执行,则在用户退出时调用此方法而不是 applicationWillTerminate:。”
【解决方案2】:

您是否尝试过将[self saveContext] 放在appDelegate 函数applicationWillTerminate: 中。您应该在终止应用程序之前保存上下文。

【讨论】:

  • 这段代码有什么用? NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];我认为默认的是nil?
  • 在更新数据模型版本时处理数据迁移。我尝试使用 nil 作为值而不是选项,但没有区别。
  • 我不认为每次应用启动时数据库都会生成一个新的。我认为问题在于您将数据插入 coredata 并忘记保存上下文。您可以在将数据插入 coredata 的位置发布代码吗?
  • 感谢 Lunayo。我设法找出我的问题。上面发布的解决方案。
猜你喜欢
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
  • 2019-08-03
  • 2015-05-15
  • 1970-01-01
  • 2020-10-23
  • 2023-03-11
  • 1970-01-01
相关资源
最近更新 更多