NSDiffableDataSourceSnapshot을 이용하여UICollectionView에 띄울 데이터를 다룰 때,
기존snapshot에 데이터를 추가하는 방식과
기존snapshot을 업데이트하는 방식을 구현하는 방법을 각각 알아보자.
가계부 앱을 예로 들어보자.
먼저, Section 에는
1. 수입, 지출, 합계를 보여주는 summary
2. 월별 데이터를 보여주는 list
typealias Item = AnyHashable
enum Section: Int {
case summary
case list
}
var datasource: UICollectionViewDiffableDataSource<Section, Item>!
private func configureCollectionView() {
datasource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView, cellProvider: { collectionView, indexPath, item in
guard let section = Section(rawValue: indexPath.section) else { return nil}
let cell = self.configureCell(for: section, item: item, collectionView: collectionView, indexPath: indexPath)
return cell
})
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.summary, .list])
snapshot.appendItems([], toSection: .summary)
snapshot.appendItems([] , toSection: .list)
datasource.apply(snapshot)
}
데이터(ex. list)에 변경이 일어날 때마다 호출되는 함수이다.
private func applySnapshot(items: [Item], section: Section) {
var snapshot = datasource.snapshot()
snapshot.appendItems(items, toSection: section)
datasource.apply(snapshot)
}
디폴트 상태인 2022년 12월 데이터 (12월 용돈)에
2022년 11월로 필터링을 설정하였으 때,
11월 데이터 (11월 통신비, 월급)이 연달아 추가되었다.

: 기존 snapshot에 있던 item을 삭제하고 새로운 item을 반영하는 방식
private func applySnapshot(items: [Item], section: Section) {
var snapshot = datasource.snapshot()
let previousItems = snapshot.itemIdentifiers(inSection: section)
snapshot.deleteItems(previousItems)
snapshot.appendItems(items, toSection: section)
datasource.apply(snapshot)
}
