如果没有可用值,则从字符串中删除"(null)"

Tho*_*lli 2 string nsstring ios

有一个应用程序,我在其中显示用户在地址中的当前位置.问题是,如果例如邮政编码或管理区域不可用,则字符串将打印(null)该值应保留的位置 - 所有其他数据都在那里.

例:

(null)19号路

(null)孟买

马哈拉施特拉邦


我想知道的是,是否可以只有一个空格而不是(null)?

我目前的代码:

 _addressLabel.text = [NSString stringWithFormat: @"%@ %@\n%@ %@\n%@",
                                 placemark.subThoroughfare, placemark.thoroughfare,
                                 placemark.postalCode, placemark.locality,
                                  placemark.administrativeArea];
Run Code Online (Sandbox Code Playgroud)

Bri*_*acy 5

使用该NSString方法很容易实现

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
Run Code Online (Sandbox Code Playgroud)

例如,在_addressLabel.text使用所有(可能是nil)值填充字符串之后,只需用期望的字符串替换不需要的字符串.例如,以下内容将解决您的问题.

_addressLabel.text = [NSString stringWithFormat: @"%@ %@\n%@ %@\n%@",
                                 placemark.subThoroughfare, placemark.thoroughfare,
                                 placemark.postalCode, placemark.locality,
                                  placemark.administrativeArea];
// that string may contain nil values, so remove them.

NSString *undesired = @"(null)";
NSString *desired   = @"\n";

_addressLabel.text = [_addressLabel.text stringByReplacingOccurrencesOfString:undesired
                                                                   withString:desired];
Run Code Online (Sandbox Code Playgroud)