I have a block of code that adds an object to an array declared outside the block with the “__block” notation (it’s an ivar). However, once the block is exited, the array contains no values. I know that it isn’t trying to add empty strings to the array, because my console prints the strings correctly. Any help would be appreciated. Here is my code:
addressOutputArray = [[NSMutableArray alloc] init];
for(CLLocation *location in locationOutputArray)
{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error)
{
if(placemarks && placemarks.count > 0)
{
CLPlacemark *topResult = [placemarks objectAtIndex:0];
NSString *address = [NSString stringWithFormat:@"%@ %@,%@ %@", [topResult subThoroughfare],[topResult thoroughfare],[topResult locality], [topResult administrativeArea]];
[addressOutputArray addObject:address];
NSLog(@"%@",address);
}
}];
[geocoder release];
}
NSLog(@"Address output array count: %d", [addressOutputArray count]);
The final log gives me a count of zero. Any help at all would be really appreciated.
The problem is that
reverseGeocodeLocationexecutes asynchronously, and you are not waiting for the calls to complete before logging the size of your output array. You might have better luck with something like:In any case, you are doing everything correctly with your block in terms of how you are setting it up and using it to modify the state of your
addressOutputArrayivar. The only problem is that you were not waiting until all your blocks had finished executing before checking the result.