带有[NSString stringWithFormat:]的Nil字符串显示为"(null)"

nmo*_*lot 18 string iphone nsstring

我有一个'Contact'类,它有两个属性:firstName和lastName.当我想显示联系人的全名时,我就是这样做的:

NSString *fullName = [NSString stringWithFormat:@"%@ %@", contact.firstName, contact.lastName];
Run Code Online (Sandbox Code Playgroud)

但是当firstName和/或lastName设置为nil时,我在fullName字符串中得到一个"(null)".为了防止它,这是我做的:

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

有人知道更好/更简洁的方法吗?

ken*_*ytm 58

假设你没事firstName<space><space>lastName:

NSString *fullName = [NSString stringWithFormat:@"%@ %@",
    contact.firstName ?: @"", contact.lastName ?: @""];
Run Code Online (Sandbox Code Playgroud)

(a ?: b是一个GCC扩展,代表a ? a : b,没有评估a两次.)

  • 你可以使用这种方法而不必在<space>上妥协,之后只需执行以下操作fullName = [fullName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; (2认同)

Ste*_*eld 7

NSString *fullName = [NSString stringWithFormat:@"%@ %@", first ? first : @"", last ? last : @""];肯定是更简洁一点,但它具有与原始代码相同的错误,即如果一个或另一个不存在,则fullName将是"firstName"或"lastName"(注意空格).因此你被迫写代码

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;
Run Code Online (Sandbox Code Playgroud)

为了它正常工作.