2012-04-09 1 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를 사용하십시오.