ios 为什么在保存父上下文时会崩溃?

ccrfmcuu  于 2023-01-22  发布在  iOS
关注(0)|答案(1)|浏览(215)
func save(handler: @escaping (NSManagedObjectContext) -> Void, completion: ((Error?)-> Void)? = nil) {
    if let rootContext = rootContext {
        let localContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
        localContext.parent = rootContext
        localContext.obtainPermanentIdsBeforeSaving()
        handler(localContext)
        guard localContext.hasChanges else {
            DispatchQueue.main.async {
                completion?(nil)
            }
            return
        }
        do {
            try localContext.save()
            try localContext.parent?.save() //here, line 65 in CoreDataManager
            DispatchQueue.main.async {
                completion?(nil)
            }
        } catch let error as NSError {
            print("❌ Core Data Save Error \(error), \(error.userInfo)")
            DispatchQueue.main.async {
                completion?(error)
            }
        }
    }
}

这是来自Firebase的报告:

brccelvz

brccelvz1#

请注意,我不是CoreDataMaven,但对我来说,这看起来像是线程问题。
您可以尝试的一个简单解决方案是将父上下文的保存调用封装在performAndWait(_:)方法中,如下所示:

func save(handler: @escaping (NSManagedObjectContext) -> Void, completion: ((Error?)-> Void)? = nil) {
    if let rootContext = rootContext {
        let localContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
        localContext.parent = rootContext
        localContext.obtainPermanentIdsBeforeSaving()
        handler(localContext)
        guard localContext.hasChanges else {
            DispatchQueue.main.async {
                completion?(nil)
            }
            return
        }
        do {
            try localContext.save()
            localContext.parent?.performAndWait {
                try localContext.parent?.save()
            }
            
            DispatchQueue.main.async {
                completion?(nil)
            }
        } catch let error as NSError {
            print("❌ Core Data Save Error \(error), \(error.userInfo)")
            DispatchQueue.main.async {
                completion?(error)
            }
        }
    }
}

相关问题