ケースに合わせてコードを調整できます。基本的に、ループを複数のメッセージに「展開」します。シーケンスを開始します[self doItForIndex:[NSNumber numberWithInt:0]];
- (BOOL)canDoitForIndex:(NSNumber *)i {
// return YES if you want to go ahead
// (e.g. test a BOOL you set in response to the user tapping a button
}
- (void)waitForIndex:(NSNumber *)i {
if ([self canDoItForIndex:i]) {
// do anything to clean up for i
// then repeat for i+1:
[self doItForIndex:[NSNumber numberWithInt:[i intValue]+1]];
} else {
[self performSelector:_cmd withObject:i afterDelay:0.01f;
}
}
- (void)doItForIndex:(NSNumber *)i {
if ([i intValue] < lastIndex) {
// do what you have to do
[self waitForIndex:i];
}
// else you're done
}
AppleのNSRunLoop
コンセプトは、処理をかなり迅速に完了することを期待しています。何かを待ってメインスレッドを拘束すると、アプリ内で他に何も起こりません。上記のコードは、「待機」を複数のメッセージ送信に分割し、アプリの応答性を維持します。