Objective-Cはカテゴリでプロトコルを実装できることに気づきました。
具体的にはカテゴリ定義で
@interface HogeClass (Foo) <BarProtocol>
と書いたらそのまま通ります。
これを利用すると、例えばモーダルビューを閉じる前に確認ダイアログを出すなどの機能をデリゲート込みで共有できます。
#import <UIKit/UIKit.h>
@interface UIViewController (Common) <UIAlertViewDelegate>
- (void) showDismissAlert;
@end
#import "UIViewController+Common.h"
@implementation UIViewController (Common)
- (void) showDismissAlert
{
UIAlertView* alert = [[UIAlertView alloc]
initWithTitle:nil
message:@"画面を閉じるよ"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil];
[alert show];
}
#pragma mark - Alert view delegate
- (void) alertView:(UIAlertView *)alertView
didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != alertView.cancelButtonIndex) {
[self dismissViewControllerAnimated:YES completion:nil];
}
}
@end
共通の振舞いについて、UIViewControllerを継承して基底クラスにしようとすると、
UITableViewControllerなどを使うときに継承階層の壁に阻まれるという問題があるのですが、
すべてカテゴリに押し込んでしまえば継承階層フリーになるので便利ですね。