2012-04-09 17 views
0

スレッドを使用してアプリケーションを開発していて、何か変なことが起こっています。スレッド順実行の問題

Iは、これらの方法を持っている:

-(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

危険!危険!

これは単にスレッドを実行する方法ではありません。どういたしまして。このコードを投げ捨て、最初からやり直す必要があります。

まず、 "同期"にsleep()を使用しないでください。

第2に、UIKitをセカンダリスレッドから削除することはできません。スレッドが表示されているように見えます。あなたができる操作は非常に限られています。

最後に、NSThreadを使用することはほとんどありません。 GCDキューまたはNSOperationQueueを使用します。