2010-03-12 107 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]];