0

コードに問題があります。スレッドを起動したいのですが、起動時に NSTimer 命令を開始できません。手伝って頂けますか?

-(void)detectionMove:(NSTimer*)timer{

    int indexArray = [[[timer userInfo] objectForKey:@"arrayIndex"] intValue];
    // do something
}



-(void)callDectectionMove:(NSNumber*)arrayIndex{

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; 

    NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];  
    [myDictionary setObject:arrayIndex forKey:@"arrayIndex"];  

    //This istruction can't lunch a detectionMove method
    [NSTimer scheduledTimerWithTimeInterval:timeToCatch target:self selector:@selector(detectionMove:) userInfo:myDictionary repeats:NO];   

    [pool   release]; 

}


-(void)detectPositionMovement{


    for(int i = 0; i< [self.arrayMovement count]; i++){

        if((actualAccelerometerX+sensibilityMovement) > [[[[self.arrayMovement      objectAtIndex:i] arrayPositionMove]objectAtIndex:0] valueX] && (actualAccelerometerX-sensibilityMovement) < [[[[self.arrayMovement      objectAtIndex:i] arrayPositionMove]objectAtIndex:0] valueX] &&
           (actualAccelerometerY+sensibilityMovement) > [[[[self.arrayMovement      objectAtIndex:i] arrayPositionMove]objectAtIndex:0] valueY] && (actualAccelerometerY-sensibilityMovement) < [[[[self.arrayMovement      objectAtIndex:i] arrayPositionMove]objectAtIndex:0] valueY] &&
           (actualAccelerometerZ+sensibilityMovement) > [[[[self.arrayMovement      objectAtIndex:i] arrayPositionMove]objectAtIndex:0] valueZ] && (actualAccelerometerZ-sensibilityMovement) < [[[[self.arrayMovement      objectAtIndex:i] arrayPositionMove]objectAtIndex:0] valueZ])
            [NSThread detachNewThreadSelector:@selector(callDectectionMove:) toTarget:self withObject:[NSNumber numberWithInt:(int)i]]; 

        }
}
4

3 に答える 3

1

ちょうど解決しました!重要なのは、メインスレッドでタイマーを開始することです

[self performSelectorOnMainThread:@selector(startTimer) withObject:nil waitUntilDone:FALSE]; 

これが役立つことを願っています

于 2011-04-14T10:33:34.740 に答える
1

本当に、本当に別のスレッドが必要ですか? そのバックグラウンド スレッドでタイマーを開始したいのですが、メイン スレッドでタイマーを開始できないのはなぜですか?

あなたの質問に答えるには: 最初の問題は: Girish が提案したようにスレッドが十分長く実行されないことです。

2 番目の問題は、スレッドの実行ループをループしていないことです。タイマーが機能するには、実行ループが必要です。

以下も参照してください。

NSThread 内で NSTimer を実行していますか?

スレッド化された NSTimer

于 2010-07-26T14:55:53.143 に答える
0

脅威で NSTimer を作成しており、タイマー オブジェクトがプールに追加されているため (クラス メソッドであるため)、タイマーが呼び出される前にタイマー オブジェクトが解放されます (タイマーが起動される前にスレッド コンテキストが終了するため)。

解決策は 2 つあります。 1. NSTimer オブジェクトに保持カウントを追加し、タイマーの作業が完了したら解放します。2. タイマーが動作するまでスレッドが終了しないようにします。

于 2010-07-26T14:45:17.393 に答える