Core Data 对象有时不会保存到永久存储中

Posted

技术标签:

【中文标题】Core Data 对象有时不会保存到永久存储中【英文标题】:Core Data objects sometimes not saved to permanent store 【发布时间】:2014-11-26 08:46:31 【问题描述】:

我在一个复杂的应用程序中遇到了一个奇怪的 Core Data 问题。该功能可以最好地描述为购物车。用户将物品放入此购物车,可以付款,等等。一开始一切正常。对象都保存到 sqlite 文件中。但过了一段时间,突然(大部分但不总是在重新启动应用程序后)一些数据丢失了。一些新的购物车不见了,而处理完的旧购物车又打开了(所以它们的状态更新没有保存)。

我的一些保存操作需要几秒钟,所以我在后台进行,而用户可以继续。我唯一能想象的是,这些保存操作会排队,并且在重新启动时会从内存中删除,而不会写入永久存储。

我尝试了以下类似的方法,但没有成功:

- (void)applicationDidEnterBackground:(UIApplication *)application

    [self saveContext];


- (void)saveContext 
    NSError *error = nil;
    if (managedObjectContext != nil) 
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) 
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        
    
    

我的后台储蓄是通过以下方式完成的:

[managedObjectContext performBlock:^
    [managedObjectContext save:nil];
    [managedObjectContext.parentContext performBlock:^
        [managedObjectContext.parentContext save:nil];
    ];
];    

【问题讨论】:

遇到保存问题的第一步是在 save: 方法中传递一个错误参数,并确定它是否被填充。 谢谢你,你说的完全正确。现在我实现了下面的后台解决方案,并在每次保存中插入错误参数。 【参考方案1】:

您在后台的保存可能已被系统终止。

Your implementation of this method has approximately five seconds to perform any tasks and return. If you need additional time to perform any final tasks, you can request additional execution time from the system by calling beginBackgroundTaskWithExpirationHandler:. In practice, you should return from applicationDidEnterBackground: as quickly as possible. If the method does not return before time runs out your app is terminated and purged from memory.

来自documentation

【讨论】:

所以我可以将我的[self saveContext] 放入bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler: 阅读:Background Execution 谢谢,我会试试这个实现。

以上是关于Core Data 对象有时不会保存到永久存储中的主要内容,如果未能解决你的问题,请参考以下文章

从内存存储中删除 Core Data 对象会将它们变成故障,但不会擦除它们

Core Data 逻辑分布?

Core Data 不会将属性更新保留到数据库

将 Core Data XML 存储同步到磁盘

将可转换的 NSAttributedString 保存到 Core Data 时出现异常奇怪的崩溃

Core Data iCloud 获取有时不会产生数据(iOS)