5

Inside the following function, I've used a block. But when I call this function, it is returned even before the block is executed. I understood that Block inturn uses the threads and executes separately so that the function doesnt wait for it to return. But, Is there any other way I could make the function execution wait, or any other way to achieve the functionality of this block without using the block itself ?

-(int)findCurrentZip
{
        CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:[self findCurrentLatitude]
                                                              longitude:[self findCurrentLongitude]];
         int zipcode;
        self.myGeocoder = [[CLGeocoder alloc] init];
        [self.myGeocoder 
         reverseGeocodeLocation:userLocation
         completionHandler: (id)^(NSArray *placemarks, NSError *error) {
             if (error == nil && [placemarks count] > 0)
             {
                 NSLog(@"Placemarks: %@",placemarks);
                 CLPlacemark *placemark = [placemarks objectAtIndex:0]; 
                 NSLog(@"Country = %@", placemark.country);
                 NSLog(@"Postal Code = %@", placemark.postalCode);
                 zipcode = (int)placemark.postalCode;
                 NSLog(@"Locality = %@", placemark.locality);
                 NSLog(@"Country%@",[placemarks lastObject]);
             }
             else if (error == nil && [placemarks count] == 0)
             {
                 NSLog(@"No results were returned.");
             }
             else if (error != nil)
             {

             }
        }];

        return zipcode;
    }
4

1 回答 1

8

首先,我建议重新考虑您的设计。与其从该方法返回 zipCode 值,不如调用 completionHandler 中的其他方法(创建协议/委托或其他)。该reverseGeocodeLocation::方法可能需要一些时间,并且您不想暂停执行等待结果的主线程。

如果您确实想阻止,您可以考虑使用(滥用?) a dispatch_semaphore_t。将其初始化为 0 并dispatch_semaphore_wait在调用reverseGeocodeLocation::. 在 completionHandler 中用dispatch_semaphore_signal.

更多信息:使用调度信号量来规范有限资源的使用

编辑:和其他人建议的一样,使用 __block 限定符声明 zipCode

于 2012-09-03T08:23:08.780 回答