2014-02-22 3 views
0

내 앱이 좀 더 복잡해질 때마다보기가 내가 원하는만큼 빠르게 새로 고쳐지지 않는 지점에 도달합니다.멀티 스레딩 및 일반적인 계층 구조 이해

예를 들어 플레이어 버튼이 있고 사용자가 해당 버튼을 클릭 할 때마다 버튼이 이미지를 변경 한 다음 플레이어가 음악을 재생하면 이미지가 오래 걸릴 것입니다.

이미지가 변경된 후 "SetNeedsdisplay"가 발생하거나 이미지가 변경된 경우에도 사용자가 "preformSelectorOnMainThred"이더라도 상관 없습니다.

난 내가 무엇을 의미하는지 보여줍니다 추가 및 코드 스냅 :

발생, 이미지의 변화이며이 발생하기 전에 애니메이션이 때문에 "callDelegate"그의 약 1 ~ 2 초가 소요 무엇
- (IBAction)playButtonPressed:(id)sender { 


//This is the image change, plus a small animation that should happen: 
dispatch_async(dispatch_get_main_queue(), ^{ 

    [self.playButtonImage setImage:[UIImage imageNamed:@"PlayDiscButtonPressedMC"]]; 
    [[self superview] setNeedsDisplay]; 

    [self performSelector:@selector(animationInsertDisk) withObject:nil]; 

}); 

//This is the methus that will call the player to start playing, by delegate. 
[self performSelector:@selector(callDelegate) withObject:nil];; 


} 

이후에 온다! 내가 "callDelegate"다음 이미지와 애니메이션이 해협 거리에서 일어날 것입니다 삭제 말할 수 있습니다!

왜 이런 일이 일어나고 있는지 이해할 수 없지만 먼저 발생하는 코드가 먼저 발생하지 않아야합니까? 주 스레드에서 발생하는 것으로 충분하지 않습니까?

도움이 필요하시면 대단히 감사하겠습니다! 감사합니다.

답변

0

나는 가까운 미래에 대한 블록

dispatch_async 일정의 모든 것을 설명하려고합니다. 예를 들어 버튼 탭 처리기에서 dispatch_async을 호출하면 메서드가 끝나고 컨트롤이 시스템에 반환 될 때까지 코드가 실행되지 않습니다.

[self performSelector:@selector(callDelegate) withObject:nil]; 

그것은 간단한 메서드 호출

[self callDelegate]; 

를 작성하는 것과 동일합니다. 그리고 그것은 막힌 호출입니다. 호출에 시간이 걸리는 경우 UI의 모든 항목이 UI 스레드에서 호출되기 때문에 대기해야합니다.

당신의 코드는 다음과 기본적으로 동일하다 : 이제

- (IBAction)playButtonPressed:(id)sender { 

    [self callDelegate]; 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self.playButtonImage setImage:[UIImage imageNamed:@"PlayDiscButtonPressedMC"]]; 

     //no need for this here. Don't try to fix bugs by adding random code. 
     //[[self superview] setNeedsDisplay]; 

     //performSelector just calls the method, so a direct call is exactly the same 
     [self animationInsertDisk]; 
    }); 
} 

, 나는 당신이 그 dispatch_async에 의해 달성하고자하는 것을 확실하지 않다. 그래서 그냥 메인 스레드에서 플레이어를 시작하고 차단하고 있다는 사실

그러나
- (IBAction)playButtonPressed:(id)sender { 
    [self.playButtonImage setImage:[UIImage imageNamed:@"PlayDiscButtonPressedMC"]]; 
    [self animationInsertDisk]; 

    [self callDelegate]; 
} 

은 "지연은"아마 발생을, 당신은 애니메이션이 즉시 시작하려는 당신은 주 스레드에서 이미 메인 스레드가 잠시 동안. [self callDelegate]에서 정확히 무엇을하고 있는지 확실하지 않지만 dispatch_async으로이 전화를 겁니다.

+0

감사합니다. 이것은 매우 도움이된다! 코드가 더 잘 작동합니다. 멀티 스레딩을 배우는 이유가 있습니까? 아니면 dispatch_async가 항상 대답입니까? – MCMatan

+0

dispatch_async * is is multithreading. 그것은 그것을 성취하는 많은 방법 중 하나 일뿐입니다. –

+0

@Catfish_Man 메인 스레드에 있고 메인 스레드에서 일정을 잡으면 실제로 멀티 스레드가 아닙니다. – Sulthan