Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nil string with [NSString stringWithFormat:] appears as "(null)"

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?

like image 355
nmondollot Avatar asked Mar 12 '10 15:03

nmondollot


1 Answers

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.)

like image 64
kennytm Avatar answered Oct 21 '22 23:10

kennytm