スレッドを使う1

web上の音楽再生を行う重い処理をスレッドに任せて画面描画を素早くする。

[NSThread detachNewThreadSelector:@selector(hoge)
						 toTarget:self withObject:nil];

UIImageの更新などは、上記では実行できないため
こちらを利用したほうがよいらしい。

[delegate performSelectorOnMainThread:@selector(hoge) withObject:nil]; 

ただし、ここで複数の引数をスレッドのメソッドに引き渡せない問題にぶつかる。
上記の、withObjectはanObjectを渡すようになっている。つまり、引数は一つとなっている。

ここで、複数の引数を渡すメソッドそのものをオブジェクトとして作成し、
それを引き渡すというNSInvocationなるものを利用する。

-(void)main{
        // ウェイティングを表示
    cell.detailTextLabel.text = @"wait";
	// セレクターの作成
	SEL selector = @selector(audioPlay:myCell:);
	// シグネチャを作成
	NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:selector];
	// invocationの作成
	NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
	[invocation setTarget:self];
	[invocation setArgument:&urlStr atIndex:2];
	[invocation setArgument:&cell atIndex:3];
	[invocation setSelector:selector];
	// スレッドで実行
	[self performSelector:@selector(performInvocation:)
			   withObject:invocation afterDelay:0.0];

}

-(void)performInvocation:(NSInvocation *)anInvocation{
	
	[anInvocation invokeWithTarget:self];

}

-(void)audioPlay:(NSString*)url myCell:(UITableViewCell *)cell{

	NSURL *myurl = [NSURL URLWithString:url];
	NSData *mydata = [NSData dataWithContentsOfURL:myurl];
	
	audioPlayer = [[AVAudioPlayer alloc] initWithData:mydata error:nil];
	cell.detailTextLabel.text = @"play";
	[audioPlayer play];
	audioPlayer.volume=0.5;
}

javaのリフレクションに相当する機能だろうか?
このようにすると、複数の引数でも1つのInvacationとしての引数にまとめられる。
デザインパターンのcommandに相当する処理であろう。