Skip to content

Instantly share code, notes, and snippets.

@laevandus
Last active January 3, 2021 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laevandus/e78944809799e272f711e6b9a4c6cfe6 to your computer and use it in GitHub Desktop.
Save laevandus/e78944809799e272f711e6b9a4c6cfe6 to your computer and use it in GitHub Desktop.
final class ViewModel: ObservableObject {
func importProducts() {
ProductAPI.getAll { result in
switch result {
case .success(let products):
self.persistenceController.container.performBackgroundTask { context in
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
let batchInsert = NSBatchInsertRequest(entityName: "Product", objects: products)
do {
let result = try context.execute(batchInsert) as! NSBatchInsertResult
print(result)
}
catch {
let nsError = error as NSError
// TODO: handle errors
}
DispatchQueue.main.async {
objectWillChange.send()
// TODO: handle errors
try? resultsController.performFetch()
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment