核心数据提交通知

时间:2012-08-03 12:04:15

标签: ios core-data notifications commit nsnotifications

我在项目中使用Core Data,我必须将用户填写的表单保存到Core Data DB中。用户重新启动应用程序后,应在TableView中显示已保存表单的列表。但是,如果用户在Core Data提交更改之前退出应用程序,则不会保存表单。有没有办法抓住我提交数据的那一刻?

这是我保存表单的方式:

if (![document.managedObjectContext save: &error]) {
    NSLog(@"DB saving error!");
}
else {
   NSLog(@"DB save OK!");
   //show alertView
 }  

我尝试使用-com.apple.CoreData.SQLDebug 1跟踪核心数据提交时刻。日志显示它在15秒后开始保存对象。

 // This is how my log output looks like
 2012-08-03 14:50:43.587 iPadAF_new[4506:707] DB save OK!
 2012-08-03 14:50:58.628 iPadAF_new[4506:2597] CoreData: sql: COMMIT

那么如何在提交后收到通知或其他内容,以便用户在保存之前无法退出应用程序?

3 个答案:

答案 0 :(得分:2)

您可以从上下文中注册NSManagedObjectContextDidSaveNotification,以找出保存上下文的时间,或者您可以观察属性hasChanges的KVO通知。我怀疑那些会起作用的背景,但是它们可能无法解决你的问题。

答案 1 :(得分:0)

如核心数据模板所示,您应该在AppDelegate中保存上下文

- (void)applicationWillTerminate:(UIApplication *)application
{
     // Saves changes in the application's managed object context before the application         terminates.
    [self saveContext];
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
             // Replace this implementation with code to handle the error appropriately.
             // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}

对我来说也是在

中保存上下文
- (void)applicationDidEnterBackground:(UIApplication *)application

解决了这个问题。

答案 2 :(得分:0)

我认为提交是指底层SQL数据库将预写日志的内容提交到主文件,但是预写日志保存在单独的持久文件中,因此从数据库保存时起它应该是安全的。

如果您检查容器,您将看到每个核心数据存储的3个文件(至少在某些时候)。

Foo.sqlite - 主数据库 Foo.sqlite-shm - 共享内存/缓存文件,一次性。 Foo.sqlite-wal - 提前写入日志。如果存在且非空,则包含尚未写入主数据库的最新更改,但如果查询需要,仍会从中返回结果。

这意味着您不需要收到提交通知,因为在该点之前数据已经安全,只是没有合并到主文件。