Swift核心数据:会话之间不存在数据。 context.save()仅适用于会话

时间:2017-04-05 07:42:07

标签: swift core-data

我正面临CoreData的一个奇怪问题。我正在开始一个操作来填充表中的初始数据。我正在('lindt', 'John') ('reese', 'bruce') ('snickers', 'William') ('chocolate', 'John') ('Milkyway', 'bruce') ('Cadbury', 'William') ('Candy', 'John') 开始操作。

applicationDidBecomeActive

我仅从// Creating child context let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) let delegate = UIApplication.sharedApplication().delegate as! AppDelegate context.parentContext = delegate.managedObjectContext // Reading data from database and printing here, shows zero number of entities always context.performBlockAndWait({ // Performing batch delete, to remove duplicacy }) context.performBlockAndWait({ // Creating entities from the JSON read from App bundle ... ... do { // Saving local context try context.save() context.parentContext?.performBlockAndWait({ do { try context.parentContext?.save() // Reading data from database and printing here, shows correct number of entities } catch { printDebug("Unable to save main context: \(error)") } }) } catch { printDebug("Unable to save main context: \(error)") } }) // Reading data from database and printing here also, shows correct number of entities 一次开始此操作,并且仅从此applicationDidBecomeActive访问entity

任何想法,问题是什么?

1 个答案:

答案 0 :(得分:0)

所以问题是使用NSBatchDeleteRequest进行批量删除。我为多种类型的 NSManagedObjectContext执行相同的代码,并且所有 NSManagedObjectContext子类。这可能就是问题所在。

当我执行fetch-all-and-delete-in-loop时,一切正常,即entities正在存储。但是当我使用NSBatchDeleteRequest一次删除所有内容时,在下一个类型 entities的{​​{1}}操作之前插入的batch-delete是被删除。

罪魁祸首是NSManagedObjectContext。我不知道为什么?我搜索但没有找到任何解决方案。所以我将就此问题发表另一个问题。