Last active
June 13, 2018 16:19
-
-
Save michael-mckenna/2ace7ac25fbcb5c0d69f84c6b23b8a4a to your computer and use it in GitHub Desktop.
Core Data Concurrency: Insert Or Update
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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