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

时间:2013-12-30 04:56:18

标签: ios multithreading cocoa-touch

所以我这样做 -

- (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];
}

有时currentLocationString会附加两个相同字符串的副本,有时则不会。这似乎是一个线程问题 - 发生了什么?在目标C中是否存在synchronized关键字,或者通过cocoa-touch来解决这个问题?

1 个答案:

答案 0 :(得分:0)

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

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