在尝试将私有上下文合并到主上下文时,应用程序有时会崩溃

时间:2017-03-12 14:04:23

标签: ios swift core-data merge nsmanagedobjectcontext

所以这很难调试。首先,这是基本设置:

我有一个每秒运行一次的方法:

@objc private func trigger() {
    appDelegate.persistentContainer.performBackgroundTask { (privateContext) in

        /* modifying database */

        do {
            // I tried setting a mergePolicy, but it didn't help
            privateContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
            try privateContext.save()
        } catch let error as NSError {
            fatalError("Couldn't save private context in Handler: \(error.debugDescription)")
        }
    }    
}

如您所见,它使用的是私有语境。

在我的appDelegate(我有主要背景)中我设置了它:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        /* more stuff */

        NotificationCenter.default.addObserver(self, selector: #selector(mergeToMainViewContext(notification:)), name: NSNotification.Name.NSManagedObjectContextDidSave, object: nil)

        return true
}

func saveContext () {
    let context = persistentContainer.viewContext
    context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy // That's what I added to try. Nothing changed though
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() 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.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

func mergeToMainViewContext(notification: Notification) {
    persistentContainer.viewContext.mergeChanges(fromContextDidSave: notification)
}

你看,我添加了一个观察者,每次私有上下文(或任何其他上下文)保存时都会触发。

然而,偶尔应用程序崩溃。大多数情况下,它会在没有任何错误消息的情况下崩溃。 Xcode告诉我它在这一行崩溃了:

persistentContainer.viewContext.mergeChanges(fromContextDidSave: notification)

就是这样:/。

有时候,它会崩溃,并表示存在合并冲突。列出的差异很小。有0.1或以上的值差异。这就是为什么我尝试使用mergePolicy,但它没有帮助。

(我会发布此错误消息,但我不知道如何重现此错误)

我不知道在哪里看,如何开始调试。有没有人有想法?

如果您需要更多信息,请告诉我们!谢谢你的帮助

0 个答案:

没有答案