Efficient way to concatenate uncertain strings in Objective-C -


i want concatenate strings variables if variables not nil. if nil, don't want include them. following code works clunky , grows proportionately more complex additional variables. can recommend more elegant way this?

nsstring *city = self.address.city== nil ? @"" : self.address.city; nsstring *state = self.address.state== nil ? @"" : self.address.state; nsstring *zip = self.address.zip== nil ? @"" : self.address.zip; nsstring *bestcity;  if (city.length>0&&state.length>0&&zip.length>0) {      bestcity = [nsstring stringwithformat: @"%@ %@ %@", city, state,zip]; } else if (city.length>0&&state.length>0) {     bestname = [nsstring stringwithformat: @"%@ %@", city,state]; } else if (city.length>0&&zip.length>0) {     bestcity = [nsstring stringwithformat: @"%@ %@", city,zip]; } else if (city.length>0&&zip.length>0) {     bestcity = [nsstring stringwithformat: @"%@ %@", city,zip]; } else if (city.length>0) {     bestcity = [nsstring stringwithformat: @"%@", city]; } else if (state.length>0) {     bestcity = [nsstring stringwithformat: @"%@", state]; } else if (zip.length>0) {     bestcity = [nsstring stringwithformat: @"%@", zip]; } else {     bestcity = @""; } 

i like:

nsmutablearray *bestcityarr = [@[] mutablecopy]; // [[nsmutablearray alloc] init];  if (city.length > 0)     [bestcityarr addobject:city];  if (state.length > 0)     [bestcityarr addobject:state];  if (zip.length > 0)     [bestcityarr addobject:zip];  nsstring *bestcity = [bestcityarr componentsjoinedbystring:@" "]; 

Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -