2012-04-09 109 views
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方法時,首先執行加載並顯示測試,然後顯示進度屏幕。

爲什麼在第一種情況下線程順序是正確執行的,而在第二種情況下不是?

我在丟什麼?

謝謝。

回答

4

危險!危險!

這根本不是做線程的方法。一點也不。你需要拋出這個代碼並重新開始。

首先,您不應該使用sleep()進行「同步」。其次,你不能用UIKit從一個輔助線程;你的線程看起來像他們正在與顯示屏混雜。您可以執行的操作非常有限。

最後,你幾乎不想再使用NSThread。使用GCD隊列或NSOperationQueue。