티스토리 뷰

prepareForReuse()는 말그대로 테이블뷰에서 셀이 재사용되기 전에 불려서 준비시키는 함수다.

그러나 꼭 써야하는 함수는 아님!

 

근데 지금까지 계속 delegate 안에 있는 tableView(_:cellForRowAt:)에서 초기화를 계속 해줬는데

왜 굳이 똑같은 행동을 하는 함수를 한 번 더 써야하나? 하는게 나의 궁금증이었음.

 

-> 그럼 공식문서를 보자

 

Discussion을 읽어보면

 

If a UITableViewCell object has a reuse identifier, the table view invokes this method just before returning the object from the UITableView method dequeueReusableCell(withIdentifier:).

UITableViewCell이 reuse identifier를 갖고 있으면, 테이블뷰는 prepareForReuse() 함수를 dequeuReusableCell(withIdentifier:)이 리턴되기 전에 부른다.

 

To avoid potential performance issues, you should only reset attributes of the cell that are not related to content, for example, alpha, editing, and selection state.

잠재적인 퍼포먼스 이슈를 피하기 위해!!! 셀의 content와 관련없는 것들(예를 들면, 알파 값, selected state 같은거)만 초기화 해주는 것이 좋다.

-> 이게 핵심... (셀의 뷰 측면의 속성을 초기화 해주는게 얘의 역할임)

 

The table view's delegate in tableView(_:cellForRowAt:) should always reset all content when reusing a cell.

셀의 content와 관련있는 것들은 tableView(_:cellForRowAt:)에서 초기화해주는게 더 맞는 개발방법(?)이었음..

 

 

 

느낀점..

1. 아무 생각없이 한 곳에서 content랑 뷰적인 측면 모두 초기화하려고 했어서 내가 이 함수의 필요성을 못 느꼈던 것

2. 구글링 하기 전에 공식문서부터 보자

 

 

공식문서 링크

https://developer.apple.com/documentation/uikit/uitableviewcell/1623223-prepareforreuse

 

Apple Developer Documentation

 

developer.apple.com

 

댓글