views:

651

answers:

2

I have a 'Contact' class with two properties : firstName and lastName. When I want to display a contact's full name, here is what I do:

NSString *fullName = [NSString stringWithFormat:@"%@ %@", contact.firstName, contact.lastName];

But when the firstName and/or lastName is set to nil, I get a "(null)" in the fullName string. To prevent it, here's what I do:

NSString *first = contact.firstName;
if(first == nil)  first = @"";
NSString *last = contact.lastName;
if(last == nil)  last = @"";
NSString *fullName = [NSString stringWithFormat:@"%@ %@", first, last];

Does someone know a better/more concise way to do this?

+5  A: 

Assuming you are fine with firstName<space> or <space>lastName:

NSString *fullName = [NSString stringWithFormat:@"%@ %@",
    contact.firstName ?: @"", contact.lastName ?: @""];

(a ?: b is a GCC extension which stands for a ? a : b, without evaluating a twice.)

KennyTM
+3  A: 

NSString *fullName = [NSString stringWithFormat:@"%@ %@", first ? first : @"", last ? last : @""]; is certainly a bit more concise, but it has the same error that your original code has which is that fullName would be "firstName " or " lastName" (note the spaces) if one or the other didn't exist. Thus you're forced to write code like

NSMutableString* fullName = [NSMutableString string];
if( contact.firstName ) { [fullName appendString:contact.firstName]; }
if( contact.firstName && contact.lastName ) { [fullName appendString:@" "]; }
if( contact.lastName ) { [fullName appendString:contact.lastName]; }
return fullName;

for it to work properly.

Steven Canfield