Because reverseGeocodeLocation
has a completion block, it is handed off to another thread when execution reaches it - but execution on the main thread will still continue onto the next operation, which is NSLog(returnAddress)
. At this point, returnAddress
hasn't been set yet because reverseGeocodeLocation
was JUST handed off to the other thread.
When working with completion blocks, you'll have to start thinking about working asynchronously.
Consider leaving reverseGeocodeLocation
as the last operation in your method, and then calling a new method with the remainder of the logic inside the completion block. This will ensure that the logic doesn't execute until you have a value for returnAddress
.
- (void)someMethodYouCall
{
NSLog(@"Begin");
__block NSString *returnAddress = @"";
[self.geoCoder reverseGeocodeLocation:self.locManager.location completionHandler:^(NSArray *placemarks, NSError *error) {
if(error){
NSLog(@"%@", [error localizedDescription]);
}
CLPlacemark *placemark = [placemarks lastObject];
startAddressString = [NSString stringWithFormat:@"%@ %@
%@ %@
%@
%@",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
returnAddress = startAddressString;
//[self.view setUserInteractionEnabled:YES];
NSLog(returnAddress);
NSLog(@"Einde");
// call a method to execute the rest of the logic
[self remainderOfMethodHereUsingReturnAddress:returnAddress];
}];
// make sure you don't perform any operations after reverseGeocodeLocation.
// this will ensure that nothing else will be executed in this thread, and that the
// sequence of operations now follows through the completion block.
}
- (void)remainderOfMethodHereUsingReturnAddress:(NSString*)returnAddress {
// do things with returnAddress.
}
Or you can use NSNotificationCenter to send a notification when reverseGeocodeLocation
is complete. You can subscribe to these notifications anywhere else you need it, and complete the logic from there. Replace [self remainderOfMethodHereWithReturnAddress:returnAddress];
with:
NSDictionary *infoToBeSentInNotification = [NSDictionary dictionaryWithObject:returnAddress forKey:@"returnAddress"];
[[NSNotificationCenter defaultCenter]
postNotificationName:@"NameOfNotificationHere"
object:self
userInfo: infoToBeSentInNotification];
}];
Here's an example of using NSNotificationCenter.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…