u16suzuの blog

日々学んだことのメモブログです。

Objective-Cのデリゲートについて調べました。

Objective-Cのデリゲートについて調べました。

  1. デリゲートとは、他のオブジェクトから仕事を任されるオブジェクトのこと。つまり、c#でいえば、イベントコールバック
  2. 一般に、delegateはプロパティとして宣言される。こんな感じ。
@property (assign) id delegate;


以下、サイトで見つけたデリゲートに使用例をプロパティを使用するよう修正したソース。delegateオブジェクトがメッセージを扱えるかを、respondsToSelector: で確認してから実行している。

@interface Foo : NSObject
{
	id delegate;
}
-(void) hello;
-(void) setDelegate:(id)anObject;
@property(assign) id delegate;
@end

@implementation Foo
-(void) hello{
	if (delegate == nil) {
		NSLog(@"hello");
	} else if ([delegate respondsToSelector:@selector(hello)]) {
		[delegate hello];		 
	}

}
@synthesize delegate;
@end


@interface Bar : NSObject
-(void) hello;
@end

@implementation Bar

-(void) hello{
	NSLog(@"こんにちは");
}

@end


#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

	Foo *f = [[[Foo alloc] init] autorelease];
	//以下の2行をコメントアウトすると、helloが出力される。
	//つまり、bオブジェクトにhelloを移譲している。
	Bar *b = [[[Bar alloc] init] autorelease];
	f.delegate = b;
	
	[f hello];
	
    [pool release];
    return 0;
}