2012-04-09 116 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。