[iOS] class가 NSObject를 상속받아야할 때 (NSObjectProtocol)
안녕하세요 아렉스입니다 ! :D
개발 간 아래와 같은 에러를 보신경험이 있나요 ?
알려주는대로 Fix 버튼 눌러볼까요 ?
헉 너무 많은 속이 비어있는 stub 함수가 생겼습니다.
너무 당황스럽군요.. 커맨드 + Z를 통해서 되돌리기 하겠습니다.
다시 처음으로 돌아와서 에러 메세지를 살펴보겠습니다. 사실 영어 보기 귀찮아서 Fix 누르곤 하잖아요 ?
Cannot declare conformance to 'NSObjectProtocol' in Swift; 'StoreObserver' should inherit 'NSObject' instead
먼저 머리 속으로 생각하면서 해석 한 뒤에 파파고로 놓친 건 없는지 다시 보는 편입니다.
StoreObserver가 NSObject를 상속하면 된다고하네요 ?
한번 알려준대로 해볼게요
오 ! 에러는 사라졌네요 !
근데 왜 그런지 궁금하지않나요 ?
해결을 도와준 NSObject부터 확인해볼까요 ?
에러문에서 Swift는 NSObjectProtocol 를 준수 선언할 수 없다고 했는데
NSObject는 이미 NSObjectProtocol 를 채택하고 있네요 !!
이젠 공식문서를 한번 봐야겠어요 !
NSObject는 Objective-C 객체라면 모두 상속하고 있는 루트 클래스이고, NSObject 상속한 클래스는 Objective-C 객체로 행동 할 수 있다고하네요
모든 Objective-C 객체들의 기본이 되는 메소드의 그룹이라고 정의하네요
간단하게 정의를 짚어봤으니, 코드에서 왜 그런지 다시 보자면
SKPaymentTransactionObserver 를 한번 살펴봐야겠네요 Jump to Definition을 통해서 정의를 보겠습니다.
아 ~
이제 흐름은 이해되나요 ? StoreObserver라는 class가 SKPaymentTransactionObserver 준수하려고 했지만,
Swift에서는 NSObjectProtocol 준수할 수 없기 때문에 StoreObserver에 NSObject 를 상속시켜서 Objective-C 객체로 취급해줘야 사용 가능합니다.
참고
https://developer.apple.com/documentation/objectivec/nsobject
NSObject | Apple Developer Documentation
The root class of most Objective-C class hierarchies, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects.
developer.apple.com
https://developer.apple.com/documentation/objectivec/nsobjectprotocol
NSObjectProtocol | Apple Developer Documentation
The group of methods that are fundamental to all Objective-C objects.
developer.apple.com