[iOS] Reusable Cell과 dispose

Charlie·2022년 10월 2일
0

reusable cell의 경우 재사용이 되기 때문에 화면 밖으로 사라진다고 해도 deinit이 되지 않는다.
그렇기 때문에 rx를 사용할 때 subscription이 dispose되지 않고 계속 유지가 되면서 문제가 일어날 수 있다.
따라서 화면 밖으로 cell이 사라질 때 subscription을 dispose 해주어야 한다.

Solution

방법은 2가지가 있을 수 있다.

1. prepareForReuse

사실 tableView(:cellForRowAt:)은 원칙적으로 cell을 재사용할 때 cell의 content를 모두 초기화 시킨다. 따라서 성능적 이유로 prepareForReuse에서는 content와 무관한 것들을 초기화해야 한다. (예를들어 alpha값, selsction state, editing 등)

override func prepareForReuse() {
        self.disposeBag = DisposeBag()
    }

따라서 아래의 방법을 사용하자.

2. didEndDisplaying

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
	guard let cell = tableView.dequeueReusableCell(withIdentifier: MyCell.identifier, for indexPath) as? MyCell else { return }
    cell.disposeBag = DisposeBag()
}

Reference

[Rx] Reuseable Cell의 흔적이 남는다
UITableView에서 RxSwift를 사용할 때 주의할 점

profile
Hello

0개의 댓글