2016-08-31 3 views
3

신속한 비동기 작업에 많은 혼란을 겪었습니다.swift : async task + completion

func buttonPressed(button: UIButton) { 
    let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) 
    dispatch_async(queue) {() -> Void in 
     // display the animation of "updating" 
     // do the math here 
     dispatch_async(dispatch_get_main_queue(), { 
      // update the UI 
     } 
    } 
} 

그러나, 나는 UI가 완료 될 내 계산을 기다리지 않고 업데이트되는 것을 발견 :

func buttonPressed(button: UIButton) { 
    // display an "animation" tell the user that it is calculating (do not want to freeze the screen 
    // do some calculations (take very long time) at the background 
    // the calculations result are needed to update the UI 
} 

내가 이런 일을하려고 노력 ... 이런 식으로 뭔가 할 원하는 것입니다 . 나는 비동기 큐의 사용에 대해 혼란 스럽다. 누구 한테 도움이 되니? 감사.

+0

인 UI를 갱신하는 배경 스레드에 다시 메인 스레드 종료 후의 계산 함수의 끝에

'// 여기에 수학을 써서 서버에 요청을합니까? – bbarnhart

+0

아니요, 꽤 오랜 시간이 걸리므로 화면을 정지시키고 싶지는 않습니다. ( – user6539552

답변

5

비동기 완료 핸들러가있는 함수가 필요합니다. 계산 호출 buttonPressed 함수 디스패치에서 completion()

func doLongCalculation(completion:() ->()) 
{ 
    // do something which takes a long time 
    completion() 
} 

func buttonPressed(button: UIButton) { 
    // display the animation of "updating" 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { 
    self.doLongCalculation { 
     dispatch_async(dispatch_get_main_queue()) { 
     // update the UI 
     print("completed") 
     } 
    } 
    } 
} 
0
dispatch_queue_t dispatchqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 

dispatch_async(dispatchqueue, ^(void){ 
    while ([self calculate]) { 
     NSLog(@"calculation finished"); 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      // update the UI 
     }); 
    } 
}); 

- (BOOL)calculate 
{ 
    //do calculation 
    //return true or false based on calculation success or failure 
    return true; 
} 
+1

기다리는 것은 꽤 나쁜 방법입니다. – vadian

+0

작동하지 않습니다. – user6539552