我有一个使用 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);
}
} ];
}
非常感谢大家的帮助:)