所以我这样做 -
- (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来解决这个问题?
答案 0 :(得分:0)
当reverseGeocodeLocation
尚未完成执行并且您收到新的位置更新时,会发生这种情况。因此,在completionHandler
中,您将字符串附加到同一个变量中。
为避免这种情况,您应在currentLocationString
内创建completionHandler
的副本。