我有两个名为 myLocality 和 myCountry 的全局 NSString 变量...
我已将 GeoCode 设置如下:
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
finishedGettingLocation = false;
if (newLocation.horizontalAccuracy < 200.0f){
[locationManager stopUpdatingLocation];
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
__block NSString *locality;
__block NSString *country;
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark * placemark in placemarks) {
locality = placemark.locality;
country = placemark.ISOcountryCode;
}
}];
do {
} while ([geoCoder isGeocoding]);
myLocality = locality;
myCountry = country;
finishedGettingLocation = true;
}
}
而我的后台线程如下:
- (void) doWork
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
finishedGettingLocation = false;
dispatch_async(dispatch_get_main_queue(), ^{
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
[locationManager startUpdatingLocation];
});
int counter = 0;
do {
[NSThread sleepForTimeInterval:.1];
counter ++;
if (counter % 200 == 0){
dispatch_async(dispatch_get_main_queue(), ^{
Toast *oToast = [Toast toastWithMessage:@"Gps pin-pointing works faster if you are outside"];
[oToast showOnView:self.view];
});
counter = 0;
}
} while (!finishedGettingLocation);
NSLog(@"%@", myCountry); // this is where I am trying to print
NSLog(@"%@", myLocality); // this is where I am trying to print
});
}
(是的,我知道这是相当草率的代码,但是,嗯.. xD)
现在,我无法弄清楚为什么当我将它们记录到其他地方的代码中时它们返回 null 。但是,当我在上面输入 log 时for
,即NSLog(@"%@", placemark.locality)
我得到了正确的值,或者至少我得到了一个值。
如何设置全局变量placemark
?