Intermittent crash when saving to Core Data

We are experiencing intermittent crashes when saving Core Data in an application that uses two peripherals connected via Core Bluetooth.

I could really use some assistance to understand the crash log here.

For some reason it seems that the following code crashes on try context.save(), which is strange since it is in a try block:

    func saveContext (_ inContext: NSManagedObjectContext? = nil) {
        if let context = inContext {
            if context.hasChanges {
                do {
                    try context.save()
                } catch {
                    let nserror = error as NSError
                    debugPrint("Failed to load persistant store: \(nserror), \(nserror.userInfo)")
                }
            }
    ...

I recommend enabling all the debugging support for Core Data in Xcode. See here for more… https://useyourloaf.com/blog/debugging-core-data/

most often, a crash during save means you created an NSManagedObject in one context, and tried to save in another context. Also, you should be doing a save within the thread owned by the context, like this


context.perform {
  // load objects
  // make changes

  try context.save()
}

I am aware that a context should not be shared between threads.

I have a method called addChunkBuffer which stores the data from one of the peripherals as it has been processed. This method does the following:

let context = CoreDataManager.shared.getContext()
context.performAndWait {
	let samples = getSamples(context)
	…
	modify some of the samples
	…
}
CoreDataManager.shared.saveContext(context)

See the attached file for the CoreDataManager class.

Intermittent crash when saving to Core Data
 
 
Q