我试图在完成处理程序中存储一个字符串值,但是它的作用域仅限于该块。如何解决这个问题?
// Do any additional setup after loading the view, typically from a nib.
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[locationManager startUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
NSString *co;
[geocoder reverseGeocodeLocation:locationManager.location
completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!");
if (error){
NSLog(@"Geocode failed with error: %@", error);
return;
}
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"placemark.country %@",placemark.country);
co = placemark.country;
//
}];
NSLog(@"%@",co);在这一行,co的值再次变为空。请告诉我,如何才能保留完成处理程序之外的值,这是我存储在完成处理程序中的。
发布于 2014-04-09 03:44:41
问题不是范围问题,而是在完成块之前调用日志。反向地理代码调用是异步的。当它完成它正在做的事情时,它将返回这个块,但是在此期间,您的方法的其余部分将执行。如果在设置该行的值后,但在完成块中打印co,则它将显示正确的值。
示例:
[geocoder reverseGeocodeLocation:locationManager.location
completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!");
if (error){
NSLog(@"Geocode failed with error: %@", error);
return;
}
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"placemark.country %@",placemark.country);
co = placemark.country;
// The completion block has returned and co has been set. The value equals placemark.country
NSLog(@"%@",co);
}];
// This log is executed before the completion handler. co has not yet been set, the value is nil
NSLog(@"%@",co);如果需要在块之外使用co变量,则应该从完成块中调用它将在其中使用的方法:
[geocoder reverseGeocodeLocation:locationManager.location
completionHandler:^(NSArray *placemarks, NSError *error) {
[self myMethodWithCountry:placemark.country];
}];
- (void)myMethodWithCountry:(NSString *)country {
// country == placemark.country
}发布于 2014-04-09 03:42:35
在完成块之前,您编写的NSLog命令将起作用。由于发生这种情况,您将得到null。您可以做的一件事是在块中打印co的值,而不是在外部执行。
或
将co的声明更改如下:
__block NSString *co= nil; 发布于 2014-04-09 03:44:03
如朱莉所建议的,在__block之前加上NSString *co;,即__block NSString *co;。这是两个下划线。
https://stackoverflow.com/questions/22952252
复制相似问题