協議定義方法簽名集合,類選擇遵循並實現。支援可選/必選方法、多協議組合、委托模式類型安全檢查。
// 基礎協議 @protocol BaseProtocol - (void)baseMethod; @end // 繼承協議 @protocol SonProtocol- (void)sonMethod; @end
// 單協議 @interface Car : NSObject@end // 多協議 @interface Car : NSObject @end
@protocol WorkerProtocol@optional - (void)doOptionalWork; // 可選實現 @required - (void)doRequiredWork; // 必須實現(默認) @end
區別於 C++:C++ 純虛函數強制全部實現,OC 協議可靈活標記。
@interface Manager : NSObject @property (weak) iddelegate; // 必須遵循 WorkerProtocol - (void)doWork; @end // 正確用法 Manager *mgr = [[Manager alloc] init]; mgr.delegate = [[WorkerImpl alloc] init]; // WorkerImpl 遵循協議 [mgr doWork]; // 編譯器報警示例 NSString *name = @"akon"; mgr.delegate = name; // ⚠️ Warning: Assigning to 'id ' from incompatible type 'NSString*'
@interface MyClass (Private) id obj; [obj conformsToProtocol:@protocol(WorkerProtocol)]weak 避免循環引用Delegate/DataSource 結尾(如 UITableViewDelegate)protocol,支援關聯類型、默認實現等更強特性