2011-08-18 43 views
2

將數組中的前三個對象(或1或2,如果數組有多大)轉換爲逗號分隔的字符串,最有效的方法是什麼?我有一種感覺,有塊的方式,但我不能工作前三項的NSArray到NSString中?

對象是樂隊,存儲在bandArray,每個樂隊的屬性包括一個bandName。

所以輸出會是這樣的

String 
"Abba"     <- when there is one object 
"Abba, Kiss"    <- when there is two objects 
"Abba, Kiss, Nirvana"  <- when there is three objects 
"Abba, Kiss, Nirvana"  <- when there is four objects. after three, names are ignored 

回答

11

您可以使用subarrayWithRange:爲:

NSString *res = [[[theArray subarrayWithRange:NSMakeRange(0, fmin(3, [theArray count]))] 
        valueForKey:@"brandName"] 
       componentsJoinedByString:@", "]; 
+0

而且,使用'[brandArray valueForKeyPath:@ 「bandName」]'方法來獲得'bandName's作爲數組 – EmptyStack

+0

@EmptyStack你說得對,我忘了這部分的質詢。編輯。 – Jilouc

+0

好的。然後我會刪除我的答案。 :-) – EmptyStack

1

你可以嘗試以下(雖然它是完全未經測試因爲我遠離我Mac

int bandCount = 1; 
NSString *bands; 
for (NSString *band in bandArray) { 
    if (bandCount > 3) break; 
    if (bandCount == 1) { 
     bands = [NSString stringWithFormat:@"%@", band]; 
    } else {   
     bands = [NSString stringWithFormat:@"%@, %@", bands, band]; 
    } 
    bandCount ++; 
} 
+0

其實,看@Jilouc的答案是因爲它比我的簡潔得多(*,也許更高效?*):) –

2
NSUInteger count = [bandArray count]; 
if (count > 3){ 
    count = 3; 
} 
NSString * resultString = [[bandArray subarrayWithRange:NSMakeRange(0,count)] componentsJoinedByString:@", "]; 
1

可能不是最快,但最簡單的,誰知道蘋果蘋果可能會做一些聰明的時候創建子陣列。

​​