iOS/Swift + Objective-c
[objective-c] 프로토콜 구현 여부 체크 (Protocol)
안경 쓴 귀니
2021. 4. 20. 01:23
반응형
프로토콜 구현 여부 체크
TestProtocol
@protocol TestProtocol <NSObject>
-(void)test;
-(void)test1:(NSString*)str;
-(void)test2:(NSString*)str str2: (NSString *)str2;
-(void)test3:(NSString*)str str2: (NSString *)str2 str3:(NSString*)str3;
@end
프로토콜 구현 여부 체크
respondsToSelector를 사용하여 프로토콜 구현 여부를 체크할 수 있다.
_testProtocol이 nil인 경우, @selector에 있는 함수가 구현되지 않은 경우는 else 구문을 탄다.
if ([_testProtocol respondsToSelector:@selector(test)]) {
[_testProtocol test];
} else {}
if ([_testProtocol respondsToSelector:@selector(test1:)]) {
[_testProtocol test1:@"1"];
} else {}
if ([_testProtocol respondsToSelector:@selector(test2:str2:)]) {
[_testProtocol test2:@"1" str2:@"2"];
} else {}
if ([_testProtocol respondsToSelector:@selector(test3:str2:str3:)]) {
[_testProtocol test3:@"1" str2:@"2" str3:@"3"];
} else {}
반응형