UIAlertViewDelegate protocol に対応することを宣言する
protocol を省略しても動作はする見たいだけど、明示的に書いておいたほうがいいですね。
// .h ファイル
// protocol は <> 内に書く。複数ある場合はカンマで区切る
@interface YourClass : NSObject <UIAlertViewDelegate>
@end
UIAlertView の delegate メソッドを定義
// .m ファイル
// UIAlertView の delegate メソッド
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
switch ( alertView.tag )
{
case 0: // tag:0 の Alert
if ( 0 == buttonIndex )
{
// [Cancel]処理
}
else
{
// [OK]処理
}
break;
case 1: // tag:1 の Alert
break;
default:
break;
}
}
UIAlertView を呼び出す部分
// .m ファイル
// ここでは、何らかのイベント時に Alert を表示するような流れ
- (IBAction)onTest:(id)sender
{
// 利用箇所
UIAlertView* alert = [[UIAlertView alloc]
initWithTitle:@"たいとる"
message:@"メッセージ"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil];
// Alert 識別のためのタグ設定
alert.tag = 1;
// 表示
[alert show];
// UIAlertView の show は同期待ちなどしません。
// なので、show で表示後にすぐにここの行に到達します。
// 画面が閉じた場合処理は delegate メソッドの方に記述します。
}
独自 protocol を作ってみる
// .h
@protocol YourClassDelegate <NSObject>
- (void)yourClass:(YourItem*)newItem;
@end
@interface YourClass : NSObject
@property id<YourDelegate> delegate;
@end
// .m
@implementation YourClass
- (void)method1
{
// デリゲートが適切に設定されているかを確認して実行
if ([self.delegate respondsToSelector:@selector(yourClass:)])
{
YourItem* item = [YourItem new];
[self.delegate yourClass:item];
}
}
@end