[iOS] TableView reloadSections

모리스·2023년 8월 9일
0

iOS

목록 보기
6/14
post-thumbnail

이번 노트에서는 iOS의 TableView에서 특정 Section만을 reloading하는 TableViwe ReloadSections를 사용하여 개발하던 중 특정 section을 reload했을 때 앱이 죽는 현상이 있어 이에 관해 작성해 보려한다.

❓원인

우선 내 코드는 다음과 같았다.

...
func tableView(_ tableView, UITableView, didSelectRowAt indexPath: IndexPath) {
	switch indexPath.section {
    case Section.section.rawValue:
        self.tableView?.reloadSections(IndexSet(integer: Section.section4.rawValue), with: .automatic)
        self.tableView?.reloadSections(IndexSet(integer: Section.section1.rawValue), with: .automatic)
        ...
      }
    }
    ...

하고자 했던거는 특정 section을 누르면 section을 reloading하여 accordion UI를 만들고자 했다. 그런데 해당 section을 누르면 앱이 crash되어 죽어버렸다...
열심히 삽질 하던 중 아주 허무하게 원인을 찾았는데.... 원인은 아주 간단했다.
reload 하고자 하는 section의 순서가 잘 못되어있었다.
예를 들어 1번 4번 section을 reload하고자 한다면 1번 section을 먼저 reload 후 4번 section을 reload 시켜줘야 했다.
왜 그런지는 추측하건데 reload시 1번 section은 accordion이 펼쳐지는 UI 4번 section은 button의 역할을 해 화살표의 방향이 바뀌는 UI인데, thread가 4번 reload를 수행하던 중 1번 reload하는 thread가 section의 높이를 변경해 4번 thread가 자신이 수행해야할 section을 못찾는(?) 것 같은 느낌을 받았다. (확신할 순 없음... 정답이 있다면 알려주세요:))
아무튼 수정된 코드는 다음과 같다.

❗결과

...
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
	switch indexPath.section {
    case Section.section1.rawValue:
    	self.tableView?.reloadSections(IndexSet(integer: Section.section1.rawValue), with: .automatic)
        self.tableView?.reloadSections(IndexSet(integer: Section.section4.rawValue), with: .automatic)
        ...
    }
}
...

이렇게 하면 잘 동작하는걸 볼 수 있다.

다만 accordion이 펼쳐지며 reload되어 UI가 변경되는데 이때 UX적으로 뭔가 어색하고 불편하게 보인다.
apple 문서를 보면 reloadSections를 할 때는 다음과 같이 가이드 되어있다.

self.tableView?.reloadSections(IndexSet(0...4), with: .automatic)

이렇게하면 1번 section부터 4번 section까지 1,2,3,4번 section을 모두 reload하게 된다. 나는 불필요한 reload는 필요없어 1번 4번만 reload하려 한 것인데.. 조금 더 찾아봐야겠다.

profile
모바일 앱 개발 노트 :)

2개의 댓글

comment-user-thumbnail
2023년 8월 9일

즐겁게 읽었습니다. 유용한 정보 감사합니다.

1개의 답글