
Objective-C에서 프로토콜(protocol)은 클래스가 특정 메서드들을 구현하는 방법임.
프로토콜은 인터페이스를 정의하지만, 실제 구현은 안함.
클래스는 하나 이상의 프로토콜을 채택(adopt)하여, 해당 프로토콜이 정의한 메서드를 구현함.
// 프로토콜 정의
@protocol My Pet <NSObject>
// 필수 메서드
- (void) doCrying;
// 선택적 메서드
@optional - (void)saySomething;
@end
클래스는 프로토콜을 채택하여 해당 프로토콜에서 정의한 메서드를 구현할 수 있음.
// Cat 인터페이스
@interface Cat : NSObject <MyPet>
{
NSString * name;
int age;
}
- (void)doCrying;
@end
@implementation MyClass
// 프로토콜의 필수 메서드 구현
- (void)doCrying {
NSLog(@"requiredMethod called");
}
// 선택적 메서드는 필요 시 구현
- (void)saySomething {
NSLog(@"optionalMethod called");
}
@end
// id 는 스위프트로는 any 이다.
프로토콜을 사용하는 예제
// 프로토콜을 채택한 클래스의 인스턴스 생성
MyClass *myObject = [[MyClass alloc] init];
// 필수 메서드 호출
[myObject requiredMethod];
// 선택적 메서드 호출 전, 해당 메서드가 구현되었는지 확인
if ([myObject respondsToSelector:@selector(optionalMethod)]) {
[myObject optionalMethod];
}
// main
int main(int argc, const char * argv[]) {
@autoreleasepool {
// MyClass 인스턴스 생성
MyClass *myObject = [[MyClass alloc] init];
// 필수 메서드 호출
[myObject requiredMethod];
// 선택적 메서드 호출 전, 해당 메서드가 구현되었는지 확인
if ([myObject respondsToSelector:@selector(optionalMethod)]) {
[myObject optionalMethod];
}
}
return 0;
}
@protocol MyProtocol 문법을 사용하여 프로토콜을 정의하며,MyProtocol>을 사용하여 프로토콜을 채택함.respondsToSelector:를 사용하여 해당 메서드가 구현되었는지 확인한 후 호출함.