NSArray的前三项成为NSString?

can*_*boy 2 iphone objective-c nsstring nsarray ios

将数组中前三个对象(或者数组有多大的1或2个)转换成逗号分隔的字符串的最有效方法是什么.我觉得有一种方法可以解决这个问题,但我无法解决这个问题

对象是Bands,存储在bandArray中,每个band的属性包括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
Run Code Online (Sandbox Code Playgroud)

Jil*_*ouc 11

你可以用subarrayWithRange:它:

NSString *res = [[[theArray subarrayWithRange:NSMakeRange(0, fmin(3, [theArray count]))] 
                  valueForKey:@"brandName"] 
                 componentsJoinedByString:@", "];
Run Code Online (Sandbox Code Playgroud)