I'm using Xcodes auto generated code for a core data swift project which includes this function in the app delegate:
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() 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.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
When I have an error with my managed objects instead of printing a message with details about the error the app crashes with an EXC_BAD_INSTRUCTION
error.
In the documentation it says:
A pointer to an NSError object. You do not need to create an NSError object. The save operation aborts after the first failure if you pass NULL.
Is the app aborting because error
is nil?
Is this a bug or is this expected behavior? (and if it's expected, what approach am I supposed to take to recover from the error instead of crashing?)
(I'm running Xcode 6.3.1)
Edit 1: error is at moc.save
function, not from abort()
- e.g. commenting out abort doesn't stop crash, and the NSLog is never reached.
Edit 2 adding screenshots of backtrace (?)
I investigated what was causing the error in the first place. I'd assumed it was a simple model validation error (trying to save an object with a missing required attribute) but all my attributes are optional.
It turns out that the problem was a Transformable attribute where I was trying to save an array of objects that don't adopt NSCoding.
I've fixed that and tried deliberately causing other types of errors (e.g. model validation) and the save
function works as expected.
Shame that I wasn't getting a sensible error for the transformable thing, but glad it's otherwise working, and a good learning experience!