DasGenie: !Scrap
« Apple Store Refund | Main | Über das File Sharing in Mac OS X... »

Samstag, 8. Januar 2005

Iterating over an NSIndexSet

Since I needed this quite a lot and the original Apple documentation isn't very helpful here, I decided to post my 2 favorite ways of iterating over an NSIndexSet:
// easy and still reasonable fast - can be reversed by using lastIndex and indexLessThanIndex:
unsigned index = [indexSet firstIndex];
while (index!=NSNotFound) {
    // do Stuff
    index=[indexSet indexGreaterThanIndex:index]) {
}
This seems a little bit inefficient, but I was made belief (by mmalc) that indexGreaterThanIndex: behaves efficient when called this way.

Nevertheless if you want full speed at possibly large sets, then go for this one:
// more complex but as efficient as you choose your buffersize
unsigned int indexBuffer[40];
unsigned int bufferIndex;
unsigned int indexCount=1;
NSRange range=NSMakeRange([indexSet firstIndex],
                          [indexSet lastIndex]-[indexSet firstIndex]+1);
while ((indexCount=[indexSet getIndexes:indexBuffer maxCount:40 inIndexRange:&range])) {
    for (bufferIndex=0;bufferIndex<indexCount;bufferIndex++) {
        unsigned int index=indexBuffer[bufferIndex];
        // do stuff
    }
}
If you know a way to reverse the direction of this one please add a comment.
20:26 - Samstag, 8. Januar 2005
Comments