2012-05-14 1 views
2

다음 블록을 어떻게 구현합니까?백그라운드에서 블록을 구현 한 다음 완료 후 주 스레드에서 다른 블록을 실행 하시겠습니까?

백그라운드에서 일부 작업을 실행해야합니다. 그런 다음 백그라운드 작업이 완료되면 일부 작업이 주 스레드에서 실행됩니다.

블록을 사용하는 이유는이 메서드에 전달 된 뷰를 업데이트해야하는 이유입니다.

- (void)doALongTask:(UIView *)someView { 

    [self doSomethingInBackground:^{ 

     // Runs some method in background, while foreground does some animation. 
     [self doSomeTasksHere]; 

    } completion:^{ 

     // After the task in background is completed, then run more tasks. 
     [self doSomeOtherTasksHere]; 

     [someView blahblah]; 

    }]; 
} 

또는이를 구현하는 쉬운 방법이 있습니까? 감사합니다. .

+0

정확하게 무엇입니까? 완성 처리기가 주 스레드에서 호출되도록'doSomethingInBackground : completion :'을 구현하는 방법? 구현하기위한 대체/더 쉬운 방법이있는 경우 ... "이"가 질문의 맥락에서 의미하는 것이 무엇이든간에? – danyowdee

답변

10

블록 작동 방식이나 주 스레드에서 완료 핸들러를 실행하는 방법에 대해 질문하는 경우 확실하지 않습니다.

코드에 따라 doSomethingInBackground를 호출하고 두 개의 블록을 매개 변수로 전달합니다. 이러한 블록은 doSomethingInBackground 메소드에서 호출하여 실행해야합니다.

- (void)doALongTask:(UIView *)someView { 

    [self doSomethingInBackground:^{ 

     // Runs some method in background, while foreground does some animation. 
     [self doSomeTasksHere]; 

    } completion:^{ 
     // After the task in background is completed, then run more tasks. 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      [self doSomeOtherTasksHere]; 
      [someView blahblah]; 
     }); 
    }]; 
} 

있다는 : 지금 당신은 당신이이처럼 보이도록 코드를 변경하는 것이 당신의 완료 핸들러가 주 스레드에서 실행되고 있는지 확인하려면

-(void)doSomethingInBackground:(void (^))block1 completion:(void (^))completion 
{ 
    // do whatever you want here 

    // when you are ready, invoke the block1 code like this 
    block1(); 

    // when this method is done call the completion handler like this 
    completion(); 
} 

: doSomethingInBackground이 같은 모양해야 당신이 쓴 코드를 기반으로 한 나의 대답.

그러나이 주석은 "백그라운드에서 일부 작업을 실행해야하는 경우 백그라운드 작업이 완료된 후 일부 작업이 주 스레드에서 실행됩니다"라고 표시하면 실제로 수행하려고하는 작업을보다 정확하게 나타낼 수 있습니다 이렇게해야합니다 :

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    // do your background tasks here 
    [self doSomethingInBackground]; 

    // when that method finishes you can run whatever you need to on the main thread 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self doSomethingInMainThread]; 
    }); 
});