목차

iOS 델리게이트(Delegate) 패턴

객체 간 상호작용 처리를 위해 사용되는 디자인 패턴. 하나의 객체가 자신의 작업 일부를 다른 객체에 위임하는 구조.

주로 iOS 개발에서 UI 동작 처리, 데이터 전달, 상태 변화 알림 등에 사용.

  • 결합도 감소: 객체 간 의존성을 낮춰 코드의 유연성 확보
  • 역할 분리: 각 객체가 자신의 역할에 집중하도록 설계
  • 주의: weak로 선언하여 강한 순환 참조 방지
// 1. Delegate Protocol 정의
protocol TaskDelegate: AnyObject {
    func taskDidComplete(result: String)
}

// 2. Delegator 클래스 (작업 수행자)
class Worker {
    weak var delegate: TaskDelegate? // Delegate는 약한 참조로 선언

    func performTask() {
        print("Worker: 작업 수행 중...")

        // 작업 완료 후 결과 생성
        let result = "작업이 성공적으로 완료되었습니다!"

        // Delegate에게 작업 완료 알림
        delegate?.taskDidComplete(result: result)
    }
}

// 3. Delegate 클래스 (작업 결과 처리자)
class Manager: TaskDelegate {
    func taskDidComplete(result: String) {
        print("Manager: Worker로부터 받은 메시지 - \(result)")
    }
}

// 4. 실행
let worker = Worker()
let manager = Manager()

// Worker의 delegate로 Manager를 설정
worker.delegate = manager

// Worker가 작업 수행
worker.performTask()