Xcode 如何等待geocodeAddressString的结果

Xcode 如何等待geocodeAddressString的结果,xcode,locking,dispatch,Xcode,Locking,Dispatch,我知道这与锁或调度组有关,但我似乎无法编写代码 在离开该方法之前,我需要知道该地址是否有效。当前线程只是溢出并返回TRUE。我试过锁具,调度员,但似乎都不正确。感谢您的帮助: - (BOOL) checkAddressIsReal { __block BOOL result = TRUE; // Lets Build the address NSString *location = [NSString stringWithFormat:@" %@ %@, %@, %@,

我知道这与锁或调度组有关,但我似乎无法编写代码

在离开该方法之前,我需要知道该地址是否有效。当前线程只是溢出并返回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;
}

文档中说,
CLGeocoder
调用主线程上的
completionHandler
。因为您可能也在从主线程调用您的方法,所以它不能等待地理编码器的回答,而不给它机会交付结果

这可以通过轮询运行循环来完成,使用一些API,如
-[nsrunlop runMode:beforeDate:


缺点是,根据模式的不同,在等待结果时,这也会传递事件和触发计时器。

只需使用块作为参数:

- (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);
                 }];
}

嗨,你最后解决了这个问题吗,我也有同样的问题。