안녕하세요. [weak self] 질문드립니다.

rlarjadn3 2023년 10월 11일 PM 11:54 59 0
rlarjadn3 Profile Image Level 2

안녕하세요. 강의를 수강하던 도중에 Swift 문법이 헷갈려서 제가 생각하는 게 맞는지 여쭤보고자 질문글을 남깁니다.

아래 코드에서 UIAlertAction의 handler 클로저는 ViewController를 약한 캡처(weak Capture)하고 있는데, 지금 같은 상황에서 꼭 약한 캡처를 해야 하는 건지 의문이 듭니다 (ARC의 기본 개념을 알고 있습니다)

ViewController가 UIAlertAction을 참조(+1)하고 있고, 동시에 UIAlertAction의 handler가 ViewController를 참조(+1)하더라도

show 메서드가 종료되면 okAction 변수도 메모리 상에서 해제되어 강한 순환 참조가 발생할 염려가 없어 보입니다. (ViewController는 show 메서드가 종료된 후 해제될 거기 때문에 - 제가 생각하는 게 맞는지 모르겠습니다)

제 생각이 맞는 건지 확인하고 싶어 질문글 작성하게 되었습니다. 답변 감사드립니다.

@IBAction func show(_ sender: Any) {
        
        let controller = UIAlertController(
            title: "Sign in to iTunes Store",
            message: nil,
            preferredStyle: .alert
        )
        controller.addTextField { idField in
            idField.placeholder = "Apple ID"
        }
        controller.addTextField { passwordField in
            passwordField.isSecureTextEntry = true
            passwordField.placeholder = "Password"
        }
        
        let okAction = UIAlertAction(title: "Ok", style: .default) { [weak self] action in
            if let fieldList = controller.textFields {
                if let idField = fieldList.first {
                    self?.idLabel.text = idField.text
                }
                
                if let passwordField = fieldList.last {
                    self?.passwordLabel.text = passwordField.text
                }
            }
        }
        controller.addAction(okAction)
        
        let cancelAction = UIAlertAction(title: "취소", style: .cancel)
        controller.addAction(cancelAction)
        
        present(controller, animated: true)
        
    }

댓글 쓰기
답변하기
마크다운이 처음이라면 [마크다운 설명서]를 확인해 보세요.