Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove "(null)" from string if no value available

In have an app where I show the user's current position in address. The problem is that if example the Postal Code or Administrative Area isn't available, the string prints (null) where that value should be staying - all the other data is there.

Example:

(null) Road No 19

(null) Mumbai

Maharashtra


What I was wondering was if it was possible to just have a blank space instead of (null)?

My current code:

 _addressLabel.text = [NSString stringWithFormat: @"%@ %@\n%@ %@\n%@",
                                 placemark.subThoroughfare, placemark.thoroughfare,
                                 placemark.postalCode, placemark.locality,
                                  placemark.administrativeArea];
like image 331
ThomasGulli Avatar asked Dec 13 '25 23:12

ThomasGulli


2 Answers

This is very easily accomplished with the NSString method

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement

For example, after you have populated your _addressLabel.text string with all of the (possibly nil) values, just replace the occurrences of the undesired string with the desired string. For example, the following will solve your problem.

_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];
like image 148
Brian Tracy Avatar answered Dec 15 '25 12:12

Brian Tracy


Use an NSMutableString, and have some if statements which append a string to it if the value isn't [NSNull null] or nil.

CLPlacemark *placemark = ...;
NSMutableString *address = [NSMutableString string];
if (placemark.subThoroughfare) {
    [address appendString:placemark.subThoroughfare];
}
if (...) {
    [address appendFormat:@"%@\n", ...];
}
// etc...
_addressLabel.text = address;
like image 39
max_ Avatar answered Dec 15 '25 14:12

max_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!