2010-03-12 54 views
18

我有一个'Contact'类,它有两个属性:firstName和lastName。 当我想显示联系人的全名,这里是我做的:无[NSString stringWithFormat:]字符串显示为“(null)”

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

但当firstName和/或lastName的设为零,我得到一个“(空)”的全名字符串。为了防止它,这里是我做什么:

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

有人知道更好/更简洁的方法来做到这一点吗?

回答

58

假设你是罚款firstName<space><space>lastName

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

a ?: bGCC extension它代表a ? a : b,没有评估a两次。)

+0

很好的例子和有用的链接 – JSA986 2012-12-31 20:00:27

+2

您可以使用此方法,而无需妥协的,只是后来的以下 全名= [全名stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]; – 2014-01-08 02:54:37

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; 

使其正常工作。

1

以下是我accompished ...

NSString *lastName = (NSString *)ABRecordCopyValue(personRef, kABPersonLastNameProperty); 
cell.text = [NSString stringWithFormat:@"%@%@",lastName?[NSString stringWithFormat:@"%@ ",lastName]:@"",(NSString *)ABRecordCopyValue(personRef, kABPersonFirstNameProperty)?:@""]; 
0

这是我做到了。它不像其他人那么紧凑,但它的可读性更强(这对我来说总是最重要的)。

它还具有从开始和结束去除尾随空白的优点。

// Remove any nulls from the first or last name 
firstName = [NSString stringWithFormat:@"%@", (firstName ? firstName : @"")]; 
lastName = [NSString stringWithFormat:@"%@", (lastName ? lastName : @"")]; 

// Concat the strings 
fullName = [NSString stringWithFormat:@"%@ %@", firstName, lastName]; 

// Remove any trailing whitespace 
fullName = NSString *newString = [oldString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
相关问题