反向地理编码追加两次 - 可能的线程问题



所以我正在这样做 -

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    if (newLocation != nil) {
        currentLocation = newLocation;
    }
    currentLocationString = [[NSMutableString alloc] initWithString:@""];
    geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error == nil && [placemarks count] > 0) {
            CLPlacemark* currentLocPlacemark = [placemarks lastObject];
            NSLog(@"FORMATTED ADDR DICT : %@", currentLocPlacemark.addressDictionary);
            [currentLocationString appendString: currentLocPlacemark.addressDictionary[@"Street"]];
            [currentLocationString appendString: @" "];
            [currentLocationString appendString: currentLocPlacemark.addressDictionary[@"City"]];
            NSLog(@"%@", currentLocationString);
            [currentLocationString appendString: @" "];
            [currentLocationString appendString: currentLocPlacemark.addressDictionary[@"Country"]];
            NSLog(@"CURRENTLOCATION STRING : %@", currentLocationString);
        } else {
            NSLog(@"%@", error.debugDescription);
        }
    } ];
    [locationManager stopUpdatingLocation];
}
有时,

当前位置字符串附加了同一字符串的两个副本,有时则不会。这似乎是一个线程问题 - 发生了什么?目标 C 中是否有同步关键字,或者通过可可触摸解决此问题的某种方法?

reverseGeocodeLocation尚未完成其执行并且您收到新的位置更新时,就会发生这种情况。因此,在 completionHandler 中,您将在同一变量中附加字符串。

为避免这种情况,您应该在completionHandler中创建currentLocationString的副本。

最新更新