The variable is null after setting it inside the block

I don’t think I understand how blocks work in this particular scenario. I am trying to get the location from CLGeocoder and save MKPlacemark after block completion. So in this method:

- (MKPlacemark *)placeMarkFromString:(NSString *)address {
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    __block MKPlacemark *place;
    [geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
        [placemarks enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSLog(@"%@", [obj description]);
        }];

        // Check for returned placemarks
        if (placemarks && [placemarks count] > 0) {
            CLPlacemark *topResult = [placemarks objectAtIndex:0];

            // Create an MKPlacemark and add it to the mapView
            place = [[MKPlacemark alloc] initWithPlacemark:topResult];
            [self.mapView addAnnotation:place];
        }

        if (error) {
            NSLog(@"Error: %@", [error localizedDescription]);
        }
    }];
    NSLog(@"%@", [place description]);
    return place;
}

When I run my code, the MKPlacemark place is added to the map. However, if I register a value, it is NULL. I think this may be due to the fact that the block is not executed immediately? That way, my NSLog can be executed first, and then executeHandler is executed. However, how do I return MKPlacemark from this method so that I can use this value elsewhere in my code? thank.

+3
source share
1 answer

"", ivar/property ( ). __block. :

self.place = [[MKPlacemark alloc] initWithPlacemark: topResult];

NSARray ivar, , , .

, NSLog (@ "% @", [ ]); .

EDIT: "" , :

typedef void (^SuccessBlock)(id);
typedef void (^FailureBlock)(NSError *);

- (void)placeMarkFromString:(NSString *)address withSuccess:(SuccessBlock)success andFailure:(FailureBlock)failure {

    ... //inside the enumerateObjectsUsingBlock block
    success(place);

    ...
    failure(error);

}
+1

All Articles