Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class TodoManager {
- ...
- enum CreateTodoError: Error {
- case noStore
- }
- func createTodo(
- title: String,
- completionHandler: @escaping (Result<Todo>) -> Void
- ) {
- guard
- let container = persistentContainer
- else {
- let error: CreateTodoError = .noStore
- completionHandler(
- .failure(error: error)
- )
- return
- }
- container.performBackgroundTask { backgroundContext in
- guard
- let description = NSEntityDescription.entity(
- forEntityName: "Todo",
- in: backgroundContext
- )
- else { fatalError("CANNOT find the entity description for Todo.") }
- backgroundContext.perform {
- let todoEntity = TodoEntity(
- entity: description,
- insertInto: backgroundContext
- )
- todoEntity.title = title
- todoEntity.createdAtDate = Date()
- do {
- try backgroundContext.save()
- let todo = try Todo(entity: todoEntity)
- completionHandler(
- .success(value: todo)
- )
- }
- catch {
- completionHandler(
- .failure(error: error)
- )
- }
- }
- }
- }
- ...
- }
Add Comment
Please, Sign In to add comment