Question

I'm try to localize a start and end point to an address string, so that I can store it into NSUserDefaults. The problem is that the method continues executing and does not set my variable.

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:@"%@ %@\n%@ %@\n%@\n%@",
                          placemark.subThoroughfare, placemark.thoroughfare,
                          placemark.postalCode, placemark.locality,
                          placemark.administrativeArea,
                          placemark.country];
    returnAddress = startAddressString;

    //[self.view setUserInteractionEnabled:YES];
}];
NSLog(returnAddress);

NSLog(@"Einde");

This is what my application debugger shows:

start
einde

If for example the address of my location is : "Mainstreet 32, CITY". Then what i would want to see is the following:

Start
Mainstreet 32, CITY
Einde

The problem is that my code does not wait for my CLGeocoder to finish, so my variable returnAddress is not set when it is returned, and it is empty.

Does anyone know how to work around this?

Was it helpful?

Solution

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:@"%@ %@\n%@ %@\n%@\n%@",
                              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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top