-
self에서 unexpected 에러가 발생하는 이유공부/iOS 2023. 12. 1. 02:36
현재 UIKit 기반으로 Codebase로 앱을 개발하고 있습니다.
해당 오류는 프로젝트 진행중에 마주했던 문제입니다.
Issue
실행 자체는 잘 되었지만 노란색 에러가 발생하는게 거슬려 찾아보게 되었습니다.
저기서 제안하는 방식대로 Fix를 하게되면 이 버튼을 실행할 때 에러가 발생하게됩니다.
'self' refers to the method 'ViewController.self', which may be unexpected. Use 'ViewController.self' to silence this warning
Solution
해결법은 간단합니다.
let으로 선언한 signupButton을 lazy var로 수정하기만 하면 됩니다.
Reason
이전 코드에서 self 의 참조에서 문제가 발생한 이유는 signupButton 변수가 초기화될 때 self가 아직 초기화되지 않았기 때문입니다.
우선 let을 사용한 코드에서, signupButton 변수가 초기화 되는 시점에서 클로저가 호출되고 있습니다.
하지만 아직 self는 초기화가 되지 않은 상태입니다.
그러다보니, self만 썼을 때 예기치않다라는 메세지가 등장했는 것이며, ViewController.self와 같이 정의해버리면 에러가 발생했던 것입니다.
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/initialization/ swift 공식문서에서 initialization 부분을 확인해보면 다음과 같은 부분이 있습니다.
저장 프로퍼티가 self보다 먼저 초기화가 된다는걸 확인할 수 있습니다.
따라서 lazy var를 사용해야합니다.
lazy var는 선언된 변수가 사용되기 전까지 초기화되지 않는다는 특징이 있습니다.
signupButton 변수가 초기화될 때 self는 이미 초기화된 상태이므로 문제없이 작동하게 됩니다.
reference
- swift docs
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/initialization/
Documentation
docs.swift.org
- stackoverflow - Xcode 13.3 warning: "'self' refers to the method '{object}.self', which may be unexpected
Xcode 13.3 warning: "'self' refers to the method '{object}.self', which may be unexpected
I just updated to Xcode 13.3 and I'm seeing several instances of a new warning that I've not seen with previous versions of Xcode. As an example, I have a simple table view cell named
stackoverflow.com
'공부 > iOS' 카테고리의 다른 글
UIKit에서 Delegate Pattern를 쓰는 이유 (0) 2023.12.21 [UIKit]키보드 위에 수정 제안을 비활성화하기 (0) 2023.12.13 [Swift] Date formatted, FormatStyle로 날짜 출력하기 (0) 2023.07.19 디자인 챌린지 (Asia Pacific) - Part 1 (0) 2023.03.06 Xcode 아이폰 빌드한 뒤에 LLDB 라고 하면서 빌드 안되는 문제 (0) 2022.11.28