【发布时间】:2013-11-06 15:34:07
【问题描述】:
我有一个使用 GPS 并在某些标签上显示实际位置的应用程序。这里是更新位置的方法:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitude.text = [NSString stringWithFormat:@"%.3f", currentLocation.coordinate.longitude];
latitude.text = [NSString stringWithFormat:@"%.3f", currentLocation.coordinate.latitude];
}
NSLog(@"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
[address sizeToFit];
NSArray *locationArray = [[NSArray alloc] initWithObjects:placemark.thoroughfare,placemark.subThoroughfare,
placemark.postalCode,placemark.locality,placemark.country, nil];
address.text = [NSString stringWithFormat:@"%@, %@\n%@ %@\n%@",
[locationArray objectAtIndex:0],
[locationArray objectAtIndex:1],
[locationArray objectAtIndex:2],
[locationArray objectAtIndex:3],
[locationArray objectAtIndex:4]];
} else {
NSLog(@"%@", error.debugDescription);
}
} ];
}
现在,有时 'locationArray' 的某些对象是 'null',而相关标签在应用程序上显示为 '(null)',这不太好。所以我需要一个'if'循环来检查'locationArray'的对象是否为'null',如果是,则不会显示。有什么想法吗?
更新
我解决了删除数组并使用@trojanfoe 的方法(稍作修改)的问题。代码如下:
- (NSString *)sanitizedDescription:(NSString *)obj {
if (obj == nil)
{
return @"";
}
return obj;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
//NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitude.text = [NSString stringWithFormat:@"%.3f", currentLocation.coordinate.longitude];
latitude.text = [NSString stringWithFormat:@"%.3f", currentLocation.coordinate.latitude];
}
NSLog(@"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
//NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
[address sizeToFit];
address.text = [NSString stringWithFormat:@"%@, %@\n%@ %@\n%@",
[self sanitizedDescription:placemark.thoroughfare],
[self sanitizedDescription:placemark.subThoroughfare],
[self sanitizedDescription:placemark.postalCode],
[self sanitizedDescription:placemark.locality],
[self sanitizedDescription:placemark.country]];
} else {
NSLog(@"%@", error.debugDescription);
}
} ];
}
非常感谢大家的帮助:)
【问题讨论】:
-
为什么要创建数组?
-
因为我试图在数组上找到解决方案,但我可以毫无问题地更改代码..
-
NSArray(及其子类)不能(除非对 API 进行一些低级滥用)包含nil(Objective-C 表示 null),所以还有别的必须在这里进行。您是否尝试过使用调试器单步调试代码? -
目前还不清楚为什么要将地标字符串放入数组中。如果您只想显示格式正确的地标地址,请参阅stackoverflow.com/questions/7848291/…。
标签: objective-c ios7 clgeocoder