I'm new to Objective-C and my C/C++ skills are quite rusty. What better time to learn iOS development(!)
I'm trying to reverse geolocate a position using the CLGeocoder class in iOS. I can successfully get the data I'm interested in (street address) inside the block/callback, however when I try to use that data to populate my variable (outside of the block) the data isn't there. It's as if the object in the block disappears before the MapView object calls it. I'm using __block which as I understand it, should allow the variable to persist outside the block, but it seems not to.
Here's the code in question:
- (void) foundLocation:(CLLocation *)loc
{
CLLocationCoordinate2D coord = [loc coordinate];
// Get our city and state from a reversegeocode lookup and put them in the subtitle field (nowString).
// reversegeocode puts that information in a CLPlacemark object
// First, create the CLGeocoder object that will get us the info
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
// Next create a CLPlacemark object that we can store what reverseGeocodeLocation will give us containing the location data
__block CLPlacemark *placemark = [[CLPlacemark alloc]init];
__block NSString *sPlacemark = [[NSString alloc]init];
// This next bit is where things go awry
[geocoder reverseGeocodeLocation:loc completionHandler:
^(NSArray *placemarks, NSError *error) {
if ([placemarks count] > 0)
{
placemark = [placemarks objectAtIndex:0];// this works!!
sPlacemark = [placemark thoroughfare]; // as does this! I can see the street address in the variable in the debugger.
}
}];
MapPoint *mp = [[MapPoint alloc] initWithCoordinate:coord
title:[locationTitleField text]
subtitle:sPlacemark];
// add it to the map view
[worldView addAnnotation:mp];
// MKMapView retains its annotations, we can release
[mp release];
// zoom region to this location
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 250, 250);
[worldView setRegion:region
animated:YES];
[locationTitleField setText:@""];
[activityIndicator stopAnimating];
[locationTitleField setHidden:NO];
[locationManager stopUpdatingLocation];
}
I haven't completely wrapped my head around 'blocks' so it's likely that's where the problem is, but I can't put my finger on exactly what.