Skip to content

Instantly share code, notes, and snippets.

@getaaron
Last active August 29, 2015 14:25
Show Gist options
  • Save getaaron/08b6ac92fd8442eff129 to your computer and use it in GitHub Desktop.
Save getaaron/08b6ac92fd8442eff129 to your computer and use it in GitHub Desktop.
Attempts to call save() on each NSManagedObjectContext in a given array. Rolls back saved changes and throws the provided error if a save fails.
/* Attempts to call save() on each NSManagedObjectContext in a given array. Rolls back saved changes and throws the provided error if a save fails. */
func saveContexts(contexts: [NSManagedObjectContext]) throws {
var successfulContextSaves = [NSManagedObjectContext]()
for context in contexts where context.hasChanges {
do {
try context.save()
successfulContextSaves += [context]
} catch {
for savedContext in successfulContextSaves {
// roll back all changes made since the last save operation
savedContext.rollback()
}
throw error
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment