[swift] IGListDiffKit과 함께하는 테이블뷰 구현

이번 글에서는 IGListDiffKit을 사용하여 테이블뷰를 구현하는 방법에 대해 알아보겠습니다. IGListDiffKit은 UICollectionView 및 UITableView와 같은 데이터 주도 인터페이스 구성 요소의 성능을 향상시키기 위해 사용되는 라이브러리입니다. 이를 통해 데이터 업데이트 및 레이아웃 업데이트를 더 효율적으로 처리할 수 있습니다.

IGListDiffKit이란?

IGListDiffKit은 Instagram에서 개발된 UIKit 프레임워크의 일부입니다. 이 라이브러리는 주어진 데이터 세트간의 차이점을 계산하고, 이를 토대로 셀을 업데이트하는 기능을 제공합니다. 테이블뷰 또는 컬렉션뷰가 아닌 다른 인터페이스 구성 요소에서도 사용할 수 있습니다.

IGListDiffKit 사용 예시

먼저, IGListDiffKit을 프로젝트에 추가해야 합니다. CocoaPods를 사용하는 경우 Podfile에 다음과 같이 추가합니다.

pod 'IGListDiffKit'

1. IGListDiffable 프로토콜 구현하기

IGListDiffable 프로토콜을 구현하여 테이블뷰의 데이터 소스에서 변경 사항을 추적할 수 있도록 합니다. 다음은 예시 코드입니다.

import IGListDiffKit

class Item: NSObject, IGListDiffable {
    let identifier: Int
    let name: String
    
    init(identifier: Int, name: String) {
        self.identifier = identifier
        self.name = name
    }
  
    // MARK: - IGListDiffable
  
    func diffIdentifier() -> NSObjectProtocol {
        return self.identifier as NSObjectProtocol
    }
  
    func isEqual(toDiffableObject object: IGListDiffable?) -> Bool {
        guard let object = object as? Item else {
            return false
        }
        return self.identifier == object.identifier && self.name == object.name
    }
}

2. 데이터 소스 및 셀 클래스 구현하기

테이블뷰의 데이터 소스 클래스와 셀 클래스를 구현합니다. IGListDiffable 프로토콜을 준수하는 객체의 배열을 데이터 소스에 저장하고, 이를 바탕으로 테이블뷰를 업데이트합니다.

class DataSource: NSObject, UITableViewDataSource {
    var items: [Item]
  
    override init() {
        self.items = []
    }
  
    // MARK: - UITableViewDataSource
  
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
  
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        let item = items[indexPath.row]
        cell.textLabel?.text = item.name
        return cell
    }
}

class ViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
  
    let dataSource = DataSource()
  
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = dataSource
    
        // 데이터 소스 초기화
        dataSource.items = [Item(identifier: 1, name: "Item A"),
                            Item(identifier: 2, name: "Item B"), 
                            Item(identifier: 3, name: "Item C")]
        
        tableView.reloadData()
    }
}

3. 데이터 업데이트

IGListDiffKit을 사용하여 데이터 업데이트를 처리합니다. 데이터의 변경 내용을 확인하고, 이를 통해 테이블뷰를 업데이트합니다.

// 새로운 데이터로 업데이트
let newItems = [Item(identifier: 1, name: "New Item A"),
                Item(identifier: 2, name: "Item B"), 
                Item(identifier: 4, name: "Item D")]

let oldItems = dataSource.items
let result = IGListDiff(oldItems, newItems, .equality)
let updates = result.0

dataSource.items = newItems
tableView.beginUpdates()
tableView.deleteRows(at: updates.deletes.map { IndexPath(row: $0, section: 0) },
                     with: .automatic)
tableView.insertRows(at: updates.inserts.map { IndexPath(row: $0, section: 0) },
                     with: .automatic)
tableView.endUpdates()

위의 예제 코드에서는 새로운 데이터로 업데이트를 수행하였습니다. IGListDiffKit을 사용하여 이전과 새로운 데이터의 차이를 계산하고, 필요한 셀을 삭제 또는 삽입합니다.

결론

IGListDiffKit은 데이터 주도 인터페이스 구성 요소의 성능을 향상시키기 위한 강력한 도구입니다. 이를 사용하여 테이블뷰나 컬렉션뷰의 데이터 업데이트를 더욱 효율적으로 처리할 수 있습니다. IGListDiffKit에 대해 더 자세히 알고 싶다면 공식 문서를 참고하세요.