簡體   English   中英

帶有[NSString stringWithFormat:]的Nil字符串顯示為“(null)”

[英]Nil string with [NSString stringWithFormat:] appears as “(null)”

我有一個'Contact'類,它有兩個屬性:firstName和lastName。 當我想顯示聯系人的全名時,我就是這樣做的:

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

但是當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];

有人知道更好/更簡潔的方法嗎?

假設你對firstName<space><space>lastName

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

a ?: b是一個GCC擴展它代表a ? a : b ,沒有評估a兩次。)

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;

為了它正常工作。

這就是我的成就......

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

這就是我做到的。 它不像其他人那么緊湊,但我覺得它更具可讀性(這對我來說總是最重要的)。

它還具有從開頭和結尾刪除尾隨空格的好處。

// 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]];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM