0

I'm developing an app using threading, and something weird is happening.

I have these methods:

-(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 and loadSavedTest follows this logic:

Open a thread which loads a progress action screen while the main thread loads the selected item.

When method loadSelectedTest is called, all works fine, the wait screen appears and when the test is loaded and the sleep time is over, the progress screen is unloaded and the selected test appears in the screen.

But when the method loadSavedTest is called, first executes the loading and shows the test and after that shows the progress screen.

Why in the first case the thread order is properly executed and in the second case isn't?

What I'm loosing?

Thanks.

rooftop
  • 3,031
  • 1
  • 22
  • 33
NemeSys
  • 555
  • 1
  • 10
  • 28

1 Answers1

4

Danger! Danger!

That simply is not the way to do threading. Not at all. You need to throw this code out and start over.

First, you shouldn't be using sleep() for "synchronization".

Secondly, you can't muck with the UIKit from a secondary thread; your threads look like they are mucking with the display. There are very very limited operations you can do.

Finally, you pretty much never want to use NSThread anymore. Use GCD queues or NSOperationQueue.

bbum
  • 162,346
  • 23
  • 271
  • 359