1

これを行う方法が少しわかりません:

アプリの「寿命」の間実行される「ワーカースレッド」を開始します。

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

それから

- (void) updateModel {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    BackgroundUpdate *update = [[BackgroundUpdate alloc] initWithTimerInterval:5];
    [[NSRunLoop currentRunLoop] run];   //keeps it going 'forever'
    [update release];
    [pool release];
}

これで、スレッドは 5 秒 (initWithTimerInterval) ごとに「ウェイクアップ」して、実行できるタスクがあるかどうかを確認します。BackGroundUpdate クラスのすべてのタスクは、現時点では時間依存のみです。「イベント依存」のものをいくつか用意したいと思います。たとえば、バックグラウンド オブジェクトをメイン スレッドから呼び出して、「speedUp」、「slowDown」、「reset」、またはオブジェクトの任意のメソッドに指示したいとします。

これを行うには、次のようなものが必要だと思いperformSelectorOnThreadますが、NSthread と Background オブジェクトへの参照を取得するにはどうすればよいですか?

4

1 に答える 1

3

Direct answer: Instead of +[NSThread detachNewThreadSelector:toTarget:withObject:], use [[NSThread alloc] initWithTarget:selector:object:]. Don't forget to call -start!

Other thoughts:

  • Consider using NSOperation/NSOperationQueue instead. Easier and more efficient for most worker thread uses.
  • Consider whether you really need to do that periodic check on a background thread. Could you just do it on the main run loop, and then throw off work onto other threads as needed? Threads aren't free.
  • Consider whether polling is the best implementation, too. Look into NSCondition and/or NSConditionLock for more efficient ways to wake up threads when something happens (like adding work to a queue), no polling necessary.
于 2010-06-24T00:20:23.813 に答える