[UIKit] UITableViewCell에서 dequeueReusableCell 사용 시 발생하는 문제 해결

iosSwift
avatar
2025.02.19
·
2 min read

UITableView에서 dequeueReusableCell(withIdentifier:)를 사용할 때 잘못된 방식으로 사용하면 앱이 크래시가 발생할 수 있다.

이 글에서는 dequeueReusableCell 관련 문제와 해결 방법을 정리한다.


문제 상황

UITableView에서 다음과 같은 오류가 발생했다.

Fatal error: Unexpectedly found nil while unwrapping an Optional value
unable to dequeue a cell with identifier CellIdentifier - must register a nib or a class for the identifier

해결 방안

  1. 셀을 dequeueReusableCell(withIdentifier:) 호출 전에 등록하지 않음

    • CellIdentifier에 해당하는 셀이 UITableView에 등록되지 않으면 nil이 반환됨

    • 강제 언래핑(as! CustomCell)을 사용하면 앱이 크래시 발생

    let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier") as! CustomCell
    • 셀을 사용하기 전에 반드시 register()를 호출하여 등록

      tableView.register(CustomCell.self, forCellReuseIdentifier: "CellIdentifier")
  2. 셀을 제대로 재사용하지 않음

    • dequeueReusableCell에서 nil이 반환되면 새로운 셀을 직접 생성하는 방식

    • 이 방식은 iOS에서 권장되지 않음

    • 메모리 관리 문제가 발생할 수 있음

    var cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier")
    if cell == nil {
        cell = CustomCell(style: .default, reuseIdentifier: "CellIdentifier") // ❌ 직접 생성
    }
    • 항상 dequeueReusableCell을 사용하고, 등록된 셀을 올바르게 캐스팅

      let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier", for: indexPath) as! CustomCell






- 컬렉션 아티클