協議 定義了一組方法簽名,聲明了實現者需提供的行為。類似 C++ 純虛類或 Java 接口,實現了「接口與實現分離」。
@required (默認) 與 @optional 方法NSObject 協議,支持多協議繼承@protocol MyProtocol <NSObject> @optional - (void)init; @required - (int)update:(int)time; @end
在介面聲明中尖括號內列出協議名:
@interface TestProtocol : NSObject <MyProtocol>
{
}
- (void)testValue:(int)value;
@end
@implementation TestProtocol
- (void)testValue:(int)value {
NSLog(@"testValue: %d", value);
}
- (int)update:(int)time {
NSLog(@"update: %d", time);
return 0;
}
- (void)printValue:(int)value {
NSLog(@"printValue: %d", value);
}
@end
利用 respondsToSelector: 動態判斷:
SEL sel = @selector(printValue:);
if ([testPtcl respondsToSelector:sel]) {
[testPtcl printValue:20];
}
可聲明協議類型變量,實現面向接口編程:
id <MyProtocol> myProtocol = [[TestProtocol alloc] init]; [myProtocol printValue:103]; // 僅可調用協議中聲明的方法 [myProtocol release];
// MyProtocol.h
@protocol MyProtocol <NSObject>
@optional - (void)printValue:(int)value;
@required - (int)printValue:(int)v1 andValue:(int)v2;
@end
// TestProtocol.h
#import "MyProtocol.h"
@interface TestProtocol : NSObject <MyProtocol>
- (void)testValue:(int)value;
@end
// TestProtocol.m 實現所有方法...
// main.m
#import "TestProtocol.h"
int main() {
@autoreleasepool {
TestProtocol *obj = [[TestProtocol alloc] init];
[obj testValue:2];
[obj printValue:30 andValue:40];
if ([obj respondsToSelector:@selector(printValue:)]) {
[obj printValue:20];
}
id<MyProtocol> proto = [[TestProtocol alloc] init];
[proto printValue:103];
[obj release]; [proto release];
}
return 0;
}