ios - 将完成处理程序中的值存储到变量中

标签 ios block local-variables

我试图在完成处理程序中存储一个字符串值,但其范围仅限于该 block 。如何解决?

// 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 的值再次变为 null。请让我知道,如何保留完成处理程序外部的值,我将其存储在完成处理程序内。

最佳答案

问题不是范围问题,而是在完成 block 之前调用日志。反向地理编码调用是异步的。每当它完成正在执行的操作时,它就会返回该 block ,但与此同时,方法的其余部分将执行。如果您在设置其值后但在完成 block 内打印该行,它将显示正确的值。

示例:

[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);

如果您需要在 block 外使用 co 变量,则应从完成 block 内调用将要使用该变量的方法:

[geocoder reverseGeocodeLocation:locationManager.location
               completionHandler:^(NSArray *placemarks, NSError *error) {

    [self myMethodWithCountry:placemark.country];

}];

- (void)myMethodWithCountry:(NSString *)country {
    // country == placemark.country
}

关于ios - 将完成处理程序中的值存储到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22952252/

相关文章:

android - 访问 iOS 指纹的哈希值?

ios - 如何删除应用程序图标角标(Badge),ios 10,swift

ios - 在 KIF 中按下后退按钮(backBarButtonItem)?

sql - Oracle:什么是单 block 与多 block IO

chat - 在 Skype 中阻止群聊

ios - 在没有弹出权限对话框的情况下添加用户通知类别

ios - 如何让循环等到 block 完成?

Ruby 数组操作内部方法

python-3.x - 局部变量如何在 python 3 的嵌套函数中工作?

Python:如何让 eval() 看到局部变量?