开发者

First three items of of NSArray into an NSString?

What would be the most efficient way of turning the first three objects (or 1 or 2 if that's how big the array is) of an array, into a string, which is comma-separated. I've got a feeling there is a way to this with blocks, but I can't work it out

The objects are Bands, stored in bandArray, and the attributes of each band include a bandName.

So the output would be something like

String
"Abba"                    <- when there is one object
"Abba, Kiss"              <- when there is two objects
"Abba, Kiss, Nirvana"     <- when ther开发者_如何学Ce is three objects
"Abba, Kiss, Nirvana"     <- when there is four objects. after three, names are ignored


You can use subarrayWithRange: for that:

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


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


You could try the following (although it's completely untested as I'm away from my 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 ++;
}


May not be the quickest but the simplest, and who know apple apple may do some smarts when creating subarrays.

[[array subarrayWithRange:NSMakeRange(0,MIN(array.length,3)] componentsJoinedByString:@","];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜