我的应用找到用户的位置,并在标签中显示地址。问题是如果某个地方不存在某些东西,例如邮政编码,那么该行会显示 (null)
。我如何使该行空白?我想它必须以某种方式在某处设置为 nil
...
请帮忙!
这是我的代码:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(@"Location: %@", newLocation);
CLLocation *currentLocation = newLocation;
[geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (error == nil && [placemarks count] > 0) {
placeMark = [placemarks lastObject];
NSString *locationString = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",
placeMark.subThoroughfare,
placeMark.thoroughfare,
placeMark.postalCode,
placeMark.locality,
placeMark.administrativeArea,
placeMark.country];
locationLabel.text = locationString;
}
else {
NSLog(@"%@", error.debugDescription);
}
}];
}
最佳答案
此代码检查所有字段是否为 nil(这会导致 <null>
输出)并替换 nil
带有空字符串的值。
NSString *locationString = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",
placeMark.subThoroughfare ?: @"",
placeMark.thoroughfare ?: @"",
placeMark.postalCode ?: @"",
placeMark.locality ?: @"",
placeMark.administrativeArea ?: @"",
placeMark.country ?: @""];
关于ios - 如果地址行不存在则将其设为空白(Objective-C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33350567/