Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Altering values within blocks in Objective - C

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.

like image 521
Mason Avatar asked Dec 06 '25 18:12

Mason


1 Answers

The problem is that reverseGeocodeLocation executes 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:

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);
             NSLog(@"Address output array count is now: %d", [addressOutputArray count]);
         }

     }];

    [geocoder release];
}

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 addressOutputArray ivar. The only problem is that you were not waiting until all your blocks had finished executing before checking the result.

like image 118
aroth Avatar answered Dec 08 '25 09:12

aroth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!