기존의 ViewController에서 직접 화면 전환을 처리하는 방식이 마음에 들지 않아 Coordinator 패턴을 적용해보았다.
✅ Coordinator 패턴
화면 전환(네비게이션) 로직을 별도의 객체로 분리하는 디자인 패턴
기존 문제점
// ViewController가 다른 ViewController를 직접 알고 있어야 함
class ExchangeRateViewController: UIViewController {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let calculatorVC = CalculatorViewController(exchangeRate: rate)
navigationController?.pushViewController(calculatorVC, animated: true)
}
}
- ViewController 간 강한 결합
- 화면 전환 로직이 UI 로직과 섞임
- 테스트하기 어려운 구조
✅ Coordinator 패턴 적용
protocol Coordinator {
var navigationController: UINavigationController { get set }
func start()
}
class MainCoordinator: Coordinator {
var navigationController: UINavigationController
func start() {
let mainVC = MainViewController()
mainVC.coordinator = self
navigationController.pushViewController(mainVC, animated: false)
}
func pushToNext() {
let nextVC = CalculatorViewController()
navigationController.pushViewController(nextVC, animated: true)
}
}
ViewController 변경
class MainViewController: UIViewController {
weak var coordinator: MainCoordinator?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// 화면 전환 로직을 Coordinator에게 위임
coordinator?.pushToNext()
}
}
Alert도 여기서 관리해주면 된다
지금처럼 단순한 앱에서는 과하게 느껴질 수도 있지만, 조금만 플로우가 더 있는 프로젝트라면 관리하기 아주 편해질 것 같다
참고
https://www.hackingwithswift.com/articles/71/how-to-use-the-coordinator-pattern-in-ios-apps
'iOS' 카테고리의 다른 글
[iOS] Coordinator 패턴 적용기 (0) | 2025.07.22 |
---|---|
[트러블슈팅] UICollectionViewCell 그림자가 초기 렌더링 시 안 보이는 문제 (0) | 2025.07.18 |
[iOS] 클로저에서 async/await로 리팩토링하기 (1) | 2025.07.08 |
[iOS] 성능 최적화: @inlinable과 lazy (1) | 2025.06.25 |
[iOS] Unit Test 기본 개념과 적용 (0) | 2025.06.23 |