Post

UIKit - performBatchUpdates 메서드

UIKit - performBatchUpdates 메서드

image

UITableView, UICollectionView에서 여러 변경 사항들(delete, insert, reload, move 등)을 하나의 트랜잭션으로 묶어 데이터 소스와 화면 상태의 불일치를 방지할 수 있게 해줌.

Apple은 beginUpdates, endUpdates 메서드보다 performBatchUpdates 메서드 사용을 권고하고 있음.

image

  • updates: insert, delete, reload, move 등의 변경 사항들을 묶어서 처리하는 block
  • completion: 모든 변경 사항의 애니메이션이 처리된 후 호출되는 클로저

performBatchUpdates 메서드가 실행될 때는 항상 delete를 먼저 처리한 후에 insert를 처리함.

insert 코드를 먼저 작성하더라도 delete가 우선적으로 실행됨.

사용 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
extension ViewController: UITableViewDelegate{
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
 
        ...

            // performBatchUpdates 메서드 실행 전 데이터 소스를 먼저 업데이트함
            self.todoManager.setTodoList(todoList: todos)

            self.tableView.performBatchUpdates {
                self.tableView.deleteRows(at: [indexPath], with: .fade)
                if isInsert{
                    self.tableView.insertRows(at: [IndexPath(row: todos.count - 1, section: 0)], with: .none)
                }
            }
        }
        
        ...
    }

Reference

  • [https://developer.apple.com/documentation/uikit/uitableview/performbatchupdates(:completion:)/](https://developer.apple.com/documentation/uikit/uitableview/performbatchupdates(:completion:)/)
  • https://skytitan.tistory.com/516
This post is licensed under CC BY 4.0 by the author.