2012-11-06 24 views
0

我知道它是與鎖或調度組,但我只是不能似乎代碼吧...我怎麼能等待結果從geocodeAddressString iPhone

我需要知道,如果地址是一個有效的地址在離開方法之前。目前線程剛好超出並返回TRUE。我試過鎖,調度員的作品,但似乎無法得到它的正確。任何幫助表示讚賞:

- (BOOL) checkAddressIsReal 
{ 
    __block BOOL result = TRUE; 

    // Lets Build the address 
    NSString *location = [NSString stringWithFormat:@" %@ %@, %@, %@, %@", streetNumberText.text, streetNameText.text, townNameText.text, cityNameText.text, countryNameText.text]; 

    // Put a pin on it if it is valid 

    CLGeocoder *geocoder = [[CLGeocoder alloc] init]; 
    [geocoder geocodeAddressString:location 
       completionHandler:^(NSArray* placemarks, NSError* error) { 
     result = [placemarks count] != 0; 
    }]; 

    return result; 
} 

回答

0

文檔說CLGeocoder調用主線程上completionHandler。由於您可能還在主線程中調用了您的方法,因此無法等待地理編碼器的答案,也沒有機會提供結果。

這將通過輪詢runloop來完成,使用一些API作爲-[NSRunLoop runMode:beforeDate:]

缺點是,根據模式的不同,這也會在等待結果的同時傳送事件和火警定時器。

+0

喜你在最後解決這個問題,我有同樣的問題。 – HernandoZ

+0

不好意思調整了我的代碼,所以它成爲一個非問題。 – Aardvark

0

只需使用塊作爲參數:

- (void) checkAddressIsRealWithComplectionHandler:(void (^)(BOOL result))complectionHandler 
{ 
    __block BOOL result = TRUE; 

    // Lets Build the address 
    NSString *location = [NSString stringWithFormat:@" %@ %@, %@, %@, %@", streetNumberText.text, streetNameText.text, townNameText.text, cityNameText.text, countryNameText.text]; 

    // Put a pin on it if it is valid 

    CLGeocoder *geocoder = [[CLGeocoder alloc] init]; 
    [geocoder geocodeAddressString:location 
       completionHandler:^(NSArray* placemarks, NSError* error) { 
        result = [placemarks count] != 0; 
        complectionHandler(result); 
       }]; 
}