如果地址行不存在,则将其设为空白 (Objective-C)

Make address lines blank if they don't exist (Objective-C)

我的应用找到用户的位置,并在标签中显示地址。问题是,如果某个地方不存在某些东西,例如邮政编码,那么该行会显示 (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);

    }

}];

}

您确实需要编写代码来检查缺少的字段并适当地处理它们。

请注意,如果缺少某些项目,则结果字符串中可能会有空行。

快速且(非常)肮脏的解决方案,但有些人可能会发现它可读:

替代placeMark.postalCode,

placeMark.postalCode ? placeMark.postalCode : @"",

对于每个元素,在 nil.

的情况下,您不希望出现任何内容(或任何其他字符串)

或者只编写自定义代码来检查局部变量中的每个元素。

--

编辑: 在远程情况下,您实际上有一个包含 "(null)" 的字符串,您可能需要考虑检查此值,再次将每一行替换为:

[placeMark.postalCode isEqualToString:@"(null)"]? @"" : placeMark.postalCode,

考虑一下,无论如何你应该在你的逻辑中更早地处理这个问题,可能在创建 placeMark 对象字符串成员时一些解析出错了。

此代码检查所有字段是否为 nil(这会导致 <null> 输出)并将 nil 值替换为空字符串。

  NSString *locationString = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",
                                placeMark.subThoroughfare ?: @"",
                                placeMark.thoroughfare ?: @"",
                                placeMark.postalCode ?: @"",
                                placeMark.locality ?: @"",
                                placeMark.administrativeArea ?: @"",
                                placeMark.country ?: @""];