我正在使用线程开发一个应用程序,并且发生了一些奇怪的事情。
我有这些方法:
-(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时,首先执行加载并显示测试,然后显示进度屏幕。
为什么在第一种情况下线程顺序正确执行而在第二种情况下不是?
我失去了什么?
感谢。
答案 0 :(得分:4)
危险!危险!
这根本不是做线程的方法。一点也不。您需要抛弃此代码并重新开始。
首先,您不应该使用sleep()
进行“同步”。
其次,你不能从次要线程中弄清UIKit
;你的线程看起来像是在弄脏显示器。您可以执行的操作非常有限。
最后,你几乎不想再使用NSThread
了。使用GCD队列或NSOperationQueue。