Why is this CLLocationCoordinate2D variable unassignable?

我的梦境 提交于 2019-12-01 14:24:59

You have to use the __block keyword if you want to assign to a variable that was defined outside the block's scope:

__block CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(0,0);

Have a look at the Blocks and Variables section of Apple's Block Programming Topics

About the variable not getting set when it compiles:

geocodeAddressDictionary:completionHandler: runs asynchronously. That means it returns immediately but the block gets executed later, when the results are available. You need to change the way you call your methods. At the moment you are probably doing something like this

self.myCoordinate = [self geocode];

What you have to do is more like this:

- (void)geocode{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder geocodeAddressDictionary:self.placeDictionary completionHandler:^(NSArray *placemarks, NSError *error) {
        if([placemarks count]) {
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            CLLocation *location = placemark.location;
            self.myCoordinate = location.coordinate;
            NSLog(@"%f, %f", coordinate.longitude, coordinate.latitude); 
        } else {
            NSLog(@"error");
        }
    }];
}

Running [self geocode] returns immediately and myCoordinate will be set when the block runs.

If you are doing it that way, note that this could lead to a reference cycle, because self is being retained by the block.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!