Is there a way to use stringWithFormat: to leave out null parts?

227 Views Asked by At

In my iOS app, I need to do some string formatting after being passed in a set of parameters and a format.

For example: %@\n%@\n%@, %@ %@ with params line1, line2, city, state, zip] would become:

line1
line2
city, state zip

Is there a way to omit the second %@\n if line2 is nil?

If it can't be done this way, is there another way to do it?

1

There are 1 best solutions below

5
jscs On

Pre-format line2, making it an empty string if it is nil:

line2 = line2 ? [line2 stringByAppendingString:@"\n"] : @"";
NSString * address = [NSString stringWithFormat:@"%@\n%@%@, %@ %@", line1, line2, city, state, zip];