iOS/Swift

[Swift] tableview가 변경되었을 때 처리하는 방법, beginUpdates() endUpdates()

YEN_ 2023. 12. 19. 15:09

 

🌻 reloadData()

table view가 변경되었다고 해서 cell 이 자동으로 추가되는 건 아니다

우리가 테이블 뷰를 업데이트 시켜주어야 하는데, 이럴 때 간단하게 사용할 수 있는 메소드가 reloadData()이다

func reloadData()

https://developer.apple.com/documentation/uikit/uitableview/1614862-reloaddata

 

reloadData() | Apple Developer Documentation

Reloads the rows and sections of the table view.

developer.apple.com

 

리로드 데이터는 셀, 섹션 헤더 및 바닥글, 인덱스 배열 등 테이블 구성에 사용된 모든 데이터를 다시 로드한다

테이블 뷰가 데이터를 완전히 다시 로드하기를 원할 때 사용하는 메소드이다

이것은 테이블 뷰를 완전 처음부터 구성하기 때문에 사용되는 리소스가 크다

 

보통은 테이블 뷰 전체를 reload할 일이 없다고 하니 우리는 다른 메소드를 사용해 볼 수 있겠다

 

 

🌻 reloadData() 대신 쓸 수 있는 메소드

✔️ 추가 insert

  // 1개 이상의 Row를 지정된 indexPath에 추가
  func insertRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation)

  // 1개 이상의 Section을 지정된 index에 추가
  func insertSections(_ sections: IndexSet, with animation: UITableView.RowAnimation)

✔️ 삭제 delete

// 1개 이상의 Row를 지정된 indexPath에서 제거
  func deleteRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation)

  // 1개 이상의 Section을 지정된 index에서 제거
  func deleteSections(_ sections: IndexSet, with animation: UITableView.RowAnimation)

✔️ 리로딩 reload

// 1개 이상의 Row를 리로딩
  func reloadRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation)

  // 1개 이상의 Section을 리로딩
  func reloadSections(_ sections: IndexSet, with animation: UITableView.RowAnimation)

 

✔️ 메소드 사용할 때 주의할 점?

위의 3가지 종류 메소드를 사용할 때는 테이블뷰가 애니메이션을 포함하여 변경되고,

변경된 뷰의 상태에 맞게 delgate와 datasource에 쿼리가 들어간다

 

위 메소드들은 단순히 보여지는 부분을 변경해주는 메소드이므로 실제 데이터에는 영향을 주지 않는다

따라서 반드시!! 메소드를 호출하기 전에 데이터를 변경해야 한다

 

self.testData.append(Todo(title: inputTitle, isComplete: false, regDate: Date().toString("yy.M.d")))
                
self.TodoListTableView.beginUpdates()
self.TodoListTableView.insertRows(at: [IndexPath(row: self.testData.count-1, section: 0)], with: .automatic)
self.TodoListTableView.endUpdates()

나의 경우, testData라는 배열에 데이터를 넣어주는 코드를 만들었기 때문에

insertRows로 테이블 뷰를 변경하기 전에 appned로 데이터를 추가하는 작업을 해 주었다

 

 

🌻 beginUpdates(), endUpdates()

셀을 지우고 나서 새로운 셀을 바로 추가하는 작업 등, 테이블 뷰를 변경하는 메소드를 계속해서 호출하는 경우가 있다

이럴 때, 메소드들은 각각 호출될 때 마다 delegate와 datasource에 쿼리가 들어간다

불필요한 쿼리가 점점 늘어나게 되는 것이다!!

간혹가다 애니메이션이 꼬이는 경우도 생긴다

 

func beginUpdates()
func endUpdates()

 

이 두 개의 메소드는 애니메이션 블록을 만든다

 

insert, delete, reload 같은 작업을 한 번의 애니메이션으로 동시에 처리할 수 있도록 해준다!!

메소드를 호출하는 부분 앞, 뒤로 beginUpdates()와 endUpdates()를 추가해주면 된다

 

해당 블록안에서 tableview 변경 메소드를 호출하면, 쿼리가 들어가는 시점이 endUpdates() 이후가 된다

 

 

✔️ 실행되는 순서

beginUpdates, endUpdates로 만든 애니메이션 블럭에서 메소드를 실행할 때 실행되는 함수의 우선순위가 있다

  1. delete, reload 계열
  2. insert, select 계열

저 우선순위로 실행되기 때문에 선언 순서대로 함수가 실행되지 않는다는 걸 명심해야 한다

 

 

 

https://developer.apple.com/documentation/appkit/nstableview/1527288-beginupdates

 

beginUpdates() | Apple Developer Documentation

Begins a group of updates for the table view.

developer.apple.com

https://developer.apple.com/documentation/uikit/uitableview/1614890-endupdates

 

endUpdates() | Apple Developer Documentation

Concludes a series of method calls that insert, delete, select, or reload rows and sections of the table view.

developer.apple.com