MENU
コンテンツ再構築中

Objective-C:スレッドについて(メインスレッド/バックグラウンドで実行する)

AVFoundationを使用したクラスからデリゲートで受け取った値を表示させるとき、謎の遅延が発生した。
そのときの解決策となった performSelectorOnMainThread や performSelectorInBackground についてのメモ。

INDEX

メインスレッド/バックグラウンドで実行する

メインスレッドで実行する
[code]
[self performSelectorOnMainThread:(SEL) withObject:(id) waitUntilDone:(BOOL)];
[/code]
バックグラウンドで実行する
[code]
[self performSelectorInBackground:(SEL) withObject:(id)];
[/code]

スレッドに関するいくつかの注意点

  • waitUntilDone:メソッドがメインスレッドで実行され終わるのを待つ
  • UIKit のオブジェクトはメインスレッド以外からアクセスしてはいけない
  • UI関連の機能はメインスレッドで実行する

withObject で複数の引数をスレッドのメソッドに引き渡す

withObjectで複数の引数を渡すためには複数の引数を渡すメソッドをオブジェクト(NSInvocation)として作成し引き渡す。

[code]
-(void)main{

// ウェイティングを表示
cell.detailTextLabel.text = @”waiting”;
// セレクターの作成
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;

}
[/code]

まとめ

何となく始めたObjective-Cも、スレッドを意識しなければいけなくなるまでになってきた。もっと頑張ろう。
今回はスレッドに関する断片的な内容ですが、時期を見て体系的にまとめられた記事にアップデートしていきたいと思います。

この記事がみなさんのお役に立ちましたら、下記「Share it」よりブックマークやSNSで共有していただければ幸いです。

Please share it!
  • URLをコピーしました!
  • URLをコピーしました!
INDEX