Skip to content

Instantly share code, notes, and snippets.

@michael-mckenna
Last active June 13, 2018 16:19
Show Gist options
  • Save michael-mckenna/2ace7ac25fbcb5c0d69f84c6b23b8a4a to your computer and use it in GitHub Desktop.
Save michael-mckenna/2ace7ac25fbcb5c0d69f84c6b23b8a4a to your computer and use it in GitHub Desktop.
Core Data Concurrency: Insert Or Update
let privateContext = CoreDataStack.generatePrivateContext()
// 1.
privateContext.perform {
// 2.
for userJSON in jsonResponse {
let id = user["id"] as! Int
// 3.
self.searchUserBy(id: 0, in: privateContext) { (user) in
if let user = user {
user.update(json: userJSON)
} else {
let user = User(context: privateContext)
user.update(json: userJSON)
}
}
// 4.
do {
try self.privateContext.save()
self.context.performAndWait {
do {
try self.context.save()
} catch {
fatalError("Failure to save context: \(error)")
}
}
} catch {
fatalError("Failure to save context: \(error)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment