2014-07-10 1 views
0

간단한 문제가 있습니다 ... 솔루션이 간단하기를 바랍니다. 블록 내부비동기 실행 블록이 완료 될 때까지 기다리는 중

__block NSString * response; //the result ! 

[deviceInfo.geocoder reverseGeocodeLocation:deviceInfo.locationProperties completionHandler: 

^(NSArray *placemarks, NSError *error) { 

    [placemarks copy]; 
    //Get nearby address 
    CLPlacemark *placemark = [placemarks objectAtIndex:0]; 

    NSLog(@"Country : %@",placemark.country); 
    response =placemark.country; 
} 
]; 

//----------------------------------------------- 
NSLog(@"Response COUNTRY : %@",response); // response = NULL /!\ 

, placemark.countryUK 같음 :

여기 내 코드입니다.

블록 외부에서 response = placemark.country을 어떻게 가질 수 있습니까?

+1

및 블록이 실제로 호출 될 때까지 그래서'response'은 채워되지 않습니다. (a) 코드의 동기 실행에 대해 알아야합니다. – trojanfoe

+0

그러면 비동기 메서드가 끝날 때까지 기다릴 수 있습니까? – Patatrack

+0

기다리는 동안 다른 작업을 수행하여 블록에서 결과 중 하나를 호출하면 UI를 업데이트하거나 수행 할 작업 목록에서 다음 작업을 수행 할 수 있습니다. – trojanfoe

답변

0

NSLog 라인이 실행될 때 완료 블록이 아직 호출되지 않았습니다. reverseGeocodeLocation은 비 블로킹 호출이므로 완료 처리기를 사용합니다.

당신이하고 싶지 않은 것은 이것을 동기식 방법으로 바꾸는 것입니다. 지오 코드 완료에 대한 응답으로 UI를 업데이트하려고한다고 가정합니다. 다음과 같이하십시오.

"[아이콘을 복사하십시오]"행이 무엇인지 알 수 없습니다. 반환 값을 무시하기 때문에 완전히 무의미합니다. * 가능성 *이 될 방법 2 'NSLog()`문 다음에 실행됩니다

[deviceInfo.geocoder reverseGeocodeLocation:deviceInfo.locationProperties completionHandler: 

^(NSArray *placemarks, NSError *error) { 

    [placemarks copy]; 
    //Get nearby address 
    CLPlacemark *placemark = [placemarks objectAtIndex:0]; 

    NSLog(@"Country : %@",placemark.country); 
    // No need for response to be a __block variable. 
    NSString *response =placemark.country; 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self updateUIWithResponse:response]; 
    } 
]; 

-(void)updateUIWithResponse:(NSString*)response 
{ 
    NSLog(@"Got a response: %@), response); 
} 
블록은 분명히 비동기 적으로 실행되는 것을
+0

감사합니다! [장소 표시 복사]; 내 텍스트를 복사/붙여 넣기 할 때 오류가 발생했습니다. – Patatrack