0

スレッドを使用してアプリを開発していますが、奇妙なことが起こっています。

私はこれらの方法を持っています:

-(void)loadSelectedTest:(int)idTest mustBeSolved:(BOOL)mustBeSolved
{
    NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(loadTestAnimation) object:nil];

    [thread2 start];

    [respuestas loadTestQuestions:idTest testWillBeSolved:mustBeSolved];

    [thread2 cancel];
    [thread2 release];

    sleep([progressAnimation animationDelayForAnimationId:lastSelectedAnimationId]);

    [progressAnimation removeFromSuperview];
}
-(void)loadTestAnimation
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    progressAnimation = [[OTTestProgressAnimation alloc] init];    
    progressAnimation.frame = respuestas.view.frame;

    [self.view addSubview:progressAnimation];

    [progressAnimation loadWithAnimationWithId:lastSelectedAnimationId title:lastSelectedTestTitle subtitle:lastSelectedTestSubtitle];

    [progressAnimation release];

    [pool release];

}

-(void)loadSavedTest:(int)idTest mustBeSolved:(BOOL)mustBeSolved
{
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(loadTestAnimation) object:nil];

    [thread start];


    [respuestas loadSavedTestQuestions:lastSelectedTestId testWillBeSolved:YES];

    [thread cancel];
    [thread release];

    sleep([progressAnimation animationDelayForAnimationId:lastSelectedAnimationId]);

    [progressAnimation removeFromSuperview];

}

loadSelectedTest と loadSavedTest は次のロジックに従います。

メインスレッドが選択されたアイテムをロードしている間に進行アクション画面をロードするスレッドを開きます。

メソッド loadSelectedTest が呼び出されると、すべて正常に動作し、待機画面が表示され、テストがロードされてスリープ時間が終了すると、進行状況画面がアンロードされ、選択されたテストが画面に表示されます。

ただし、メソッド loadSavedTest が呼び出されると、最初にロードが実行されてテストが表示され、その後進行状況画面が表示されます。

最初のケースではスレッドの順序が正しく実行され、2 番目のケースでは正しく実行されないのはなぜですか?

私が失っているものは何ですか?

ありがとう。

4

1 に答える 1

4

危険!危険!

それは単にスレッド化を行う方法ではありません。全くない。このコードを捨てて最初からやり直す必要があります。

sleep()まず、 「同期」には使用しないでください。

UIKit第二に、あなたは二次スレッドからをいじることはできません。あなたのスレッドは、ディスプレイをいじくり回しているように見えます。実行できる操作は非常に限られています。

最後に、あなたはもうほとんど使いたくないでしょNSThreadう。GCDキューまたはNSOperationQueueを使用します。

于 2012-04-09T18:14:46.693 に答える