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;
}
First, I would suggest to rethink your design. Instead of returning the zipCode value from this method, call into some other method in the completionHandler (create a protocol / delegate or whatever). The
reverseGeocodeLocation::method can take some time, and you don’t want to pause execution of the main thread waiting on the result.If you do want to block though, you might consider using (abusing?) a
dispatch_semaphore_t. Initialize it to 0 anddispatch_semaphore_waitafter the call toreverseGeocodeLocation::. In the completionHandler signal it withdispatch_semaphore_signal.More information: Using Dispatch Semaphores to Regulate the Use of Finite Resources
edit: and like others suggested, declare zipCode with a __block qualifier