I’m baffled as to why I cannot access my global variable again after it has been through a block. Here is my code:
__block NSString *latitude;
__block NSString *longitude;
CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
[geoCoder geocodeAddressString:location completionHandler:^(NSArray* placemarks, NSError* error)
{
for (CLPlacemark* aPlacemark in placemarks)
{
CLLocation *latLong = aPlacemark.location;
latitude = [NSString stringWithFormat:@"%f", latLong.coordinate.latitude];
longitude = [NSString stringWithFormat:@"%f", latLong.coordinate.longitude];
//works fine
NSLog(@"CLLOCATION SSSSSSSSSSSSSSSSSSSSSS LAT: %@, LONG: %@", latitude, longitude);
}
}];
//no bueno
NSLog(@"CLLOCATION SSSSSSSSSSSSSSSSSSSSSS LAT: %@, LONG: %@", latitude, longitude);
Now I’ve tried initializing my NSStrings in different ways:
__block NSString *latitude = @"";
__block NSString *longitude = @"";
and:
__block NSMutableString *latitude = [NSMutableString string];
__block NSMutableString *longitude = [NSMutableString string];
But I just wind up getting empty strings when I am accessing the variables outside of the block.
This is particularly baffling because in Apple’s documentation http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/bxGettingStarted.html#//apple_ref/doc/uid/TP40007502-CH7-SW1
, they’re able to set variables outside of blocks, use them, and retrieve them just fine.
Okie doke, sounds like a couple of issues (one, none or all may apply, it’s hard to tell within the context you’ve provided):
1 – “But I just wind up getting empty strings when I am accessing the variables outside of the block.”
Depends when you’re accessing them outside the block. This is because there is no guarantee that latitude and longitude will have been populated at the time of querying them. The block provided is a completion handler for CLGeocoder; it will be called when the geocoder has found locations of interest. Being able to retrieve location data, and to do a search based on that location takes time, and the NSLog statement straight after has a high probability of being called before any ‘placemarks’ have been found.
2 – *”IOS5 __block variable throws EXC_BAD_ACCESS outside scope”*
You are assigning the following in the block:
stringWithFormatis a method that returns an autoreleased value, but you’re not retaining them anywhere. If you’re not using ARC (see https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html for ARC in memory management terms, and http://developer.apple.com/library/mac/#releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html generally), then this will cause issues when accessing the values elsewhere, as you’re accessing an object that no longer exists. If you are using ARC, then this shouldn’t be a problem, as the variables will be strong by default, and retain the value for you.