某天讀文件時看到「協定可以繼承」這件事,於是動手寫了個小 demo 驗證。結論是:子協定自動繼承父協定的 @required 與 @optional 宣告,實作子協定的類別必須滿足父協定的必要方法。以下是可以直接跑的完整程式。
@protocol OneDelegate <NSObject> @required - (void)backStr:(NSString *)str; @end
@protocol TwoDelegate <OneDelegate> @optional - (void)backInt:(int)i; @end
寫法就是把父協定名稱放進角括號裡,與繼承 NSObject 的語法形式一致。
#import "ViewController2.h" @interface ViewController : UIViewController <TwoDelegate> @end
這裡就能驗證重點:即使只宣告遵守 TwoDelegate,編譯器仍會要求實作 OneDelegate 的 backStr:,因為它是 @required。
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(50, 50, 200, 100);
button.backgroundColor = [UIColor yellowColor];
[button setTitle:@"into VC2" forState:UIControlStateNormal];
[button addTarget:self action:@selector(push)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)push {
ViewController2 *vc = [[ViewController2 alloc] init];
vc.delegate = self;
[self presentViewController:vc animated:YES completion:^{}];
}
// 來自父協定 OneDelegate
- (void)backStr:(NSString *)str {
NSLog(@"%@", str);
}
// 來自子協定 TwoDelegate
- (void)backInt:(int)i {
NSLog(@"%d", i);
}
@interface ViewController2 : UIViewController @property (nonatomic, unsafe_unretained) id delegate; @end
這裡刻意用 unsafe_unretained 而非 assign,是為了避免循環參考;在現代專案中更建議改用 weak 並加上協定型別限制,例如 id<TwoDelegate>,讓編譯器能檢查方法呼叫。
- (void)backStrBtn {
if (self.delegate &&
[self.delegate respondsToSelector:@selector(backStr:)]) {
[self.delegate backStr:@"這個是代理1的方法"];
}
}
- (void)backIntBtn {
if (self.delegate &&
[self.delegate respondsToSelector:@selector(backInt:)]) {
[self.delegate backInt:2];
NSLog(@"這是繼承而來的方法");
}
}
因為 backInt: 標記為 @optional,呼叫前必須用 respondsToSelector: 確認;而 backStr: 是 @required,理論上一定存在,但加上判斷也無妨,防禦性寫法在 delegate 為 nil 時尤其有用。
當一組回呼有明確的「基礎能力」與「延伸能力」之分時特別合適。例如基礎協定定義資料載入完成的通知,延伸協定再加上分頁、篩選等進階行為;使用方可以只要求基礎協定,需要更多功能時才升級宣告,不必一次背下所有方法。