objective-cで自分でdelegateを実装する方法

PaintingViewというクラスでtouchesEnded:withEvent:メソッドが呼ばれたときに
paintingViewDidTouchesEnded というメソッドで通知したいときを例として。

1. 通知メソッドのプロトコルを作る

@protocol PaintingViewDelegate
-(void) paintingViewDidTouchesEnded;
@end

2. 通知を送るクラスの実装

a. 1.のプロトコルを採用したid型のインスタンス変数を作る
この変数に通知先のオブジェクトへのポインタが入る

@interface PaintingView : UIView {
id delegate;
}
@end


b. そのプロパティを作る

(@interface内で)
@property(nonatomic, assign) id delegate;
(@implementation内で)
@synthesize delegate;


c. a.の変数に入っているポインタが指すインスタンスにおいて実装されているであろう
通知メソッドを、通知したい場所で実行する
その際、本当に通知メソッドが実装しているかrespondsToSelector:を使って確かめる


-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if ([self.delegate respondsToSelector:@selector(paintingViewDidTouchesEnded)])
[self.delegate paintingViewDidTouchesEnded];
}

3. 通知を受けるクラスの実装

a. 通知を送るクラスのインスタンスを作った後で、2.のa.の変数にselfを入れる

PaintingView *paintingView = [[PaintingView alloc] init];
paintingView.delegate = self;


b. 通知メソッドを実装してしたいことをする

-(void) paintingViewDidTouchesEnded {
ほにゃらら;
}


参考URL
http://blog.livedoor.jp/faulist/archives/1483024.html
http://d.hatena.ne.jp/shunsuk/20100604/1275651120
http://vivacocoa.jp/objective-c3e/supplement_b.html