Guest User

Untitled

a guest
May 25th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. class TodoManager {
  2.  
  3. ...
  4.  
  5. enum CreateTodoError: Error {
  6.  
  7. case noStore
  8.  
  9. }
  10.  
  11. func createTodo(
  12. title: String,
  13. completionHandler: @escaping (Result<Todo>) -> Void
  14. ) {
  15.  
  16. guard
  17. let container = persistentContainer
  18. else {
  19.  
  20. let error: CreateTodoError = .noStore
  21.  
  22. completionHandler(
  23. .failure(error: error)
  24. )
  25.  
  26. return
  27.  
  28. }
  29.  
  30. container.performBackgroundTask { backgroundContext in
  31.  
  32. guard
  33. let description = NSEntityDescription.entity(
  34. forEntityName: "Todo",
  35. in: backgroundContext
  36. )
  37. else { fatalError("CANNOT find the entity description for Todo.") }
  38.  
  39. backgroundContext.perform {
  40.  
  41. let todoEntity = TodoEntity(
  42. entity: description,
  43. insertInto: backgroundContext
  44. )
  45.  
  46. todoEntity.title = title
  47.  
  48. todoEntity.createdAtDate = Date()
  49.  
  50. do {
  51.  
  52. try backgroundContext.save()
  53.  
  54. let todo = try Todo(entity: todoEntity)
  55.  
  56. completionHandler(
  57. .success(value: todo)
  58. )
  59.  
  60. }
  61. catch {
  62.  
  63. completionHandler(
  64. .failure(error: error)
  65. )
  66.  
  67. }
  68.  
  69. }
  70.  
  71. }
  72.  
  73. }
  74.  
  75. ...
  76.  
  77. }
Add Comment
Please, Sign In to add comment