将数组中前三个对象(或者数组有多大的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
答案 0 :(得分:11)
您可以使用subarrayWithRange:
:
NSString *res = [[[theArray subarrayWithRange:NSMakeRange(0, fmin(3, [theArray count]))]
valueForKey:@"brandName"]
componentsJoinedByString:@", "];
答案 1 :(得分:2)
NSUInteger count = [bandArray count];
if (count > 3){
count = 3;
}
NSString * resultString = [[bandArray subarrayWithRange:NSMakeRange(0,count)] componentsJoinedByString:@", "];
答案 2 :(得分: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 ++;
}
答案 3 :(得分:1)
可能不是最快但最简单的,谁知道苹果苹果在创建子阵列时可能会做一些聪明的事。
[[array subarrayWithRange:NSMakeRange(0,MIN(array.length,3)] componentsJoinedByString:@","];