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?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With