核心数据提交通知

问题描述 投票:1回答:3

我在我的项目中使用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

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

ios core-data notifications commit nsnotifications
3个回答
2
投票

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


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

解决了这个问题。


0
投票

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.