[트러블 슈팅] 비동기 처리 2

z-wook·2023년 8월 6일
0

트러블 슈팅

목록 보기
2/6
post-thumbnail

문제 상황


tableView cell을 클릭하면 완료 표시가 나타나야 하지만 tableView(_:didSelectRowAt:) 메서드가 실행조차 되지 않는 상태


문제 상황까지의 순서

  1. cell을 클릭하고 업데이트 하는 과정중 비동기 처리를 한 부분이 있기 때문에 tableView(_:didSelectRowAt:) 메서드를 async 키워드를 사용해서 비동기 호출을 함
  2. Todo 완료를 위해 cell을 클릭하면 didSelectRowAt 메서드가 호출되지 않음

문제 상황의 코드

private func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) async {
        var selectedTodo = todoManager.getTodoList(date: viewModel?.getDate)[indexPath.row]
        selectedTodo.done = !selectedTodo.done
        if await todoManager.updateTodo(todo: selectedTodo) == true {
            tableView.reloadRows(at: [indexPath], with: .automatic)
        }
    }

원인 추론

tableView(_:didSelectRowAt:) 메서드를 비동기로 호출하기 전까지 문제없이 동작했지만 비동기로 호출하면 동작하지 않는다.
따라서 메서드를 비동기 호출하면 안된다.


수정 및 조치

tableView(_:didSelectRowAt:) 메서드를 비동기로 변경하지 않고, 내부의 비동기 작업만을 처리해야 한다.


⭐️ 문제 해결 ⭐️

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var selectedTodo = todoManager.getTodoList(date: viewModel?.getDate)[indexPath.row]
        selectedTodo.done = !selectedTodo.done
        
        Task {
            if await todoManager.updateTodo(todo: selectedTodo) == true {
                DispatchQueue.main.async {
                    tableView.reloadRows(at: [indexPath], with: .automatic)
                }
            }
        }
    }


이제 cell을 클릭하면 완료 표시가 되는 것을 볼 수 있습니다.

profile
🍎 iOS Developer

0개의 댓글