NSIndexSet block enumeration gotcha
May 10 2012

If you use NSIndexSet’s block enumerators in your iOS or Mac app code, you should beware of a bug I’ve encountered when using [NSIndexSet enumerateIndexesInRange:options:block:].

In short: it will barf and throw an exception if you provide it a range of {0, 0}. It will not barf on {1, 0}, or other ranges, which makes it insidiously easy to let this bug affect your own code.

I’ve submitted a radar ticket, but in the meantime if you use these methods you’ll need to add a check for this case, like so:

NSIndexSet * indexSet = [NSIndexSet indexSet];
NSRange range = NSMakeRange(0, 0);
if (range.length > 0)
{
  [indexSet enumerateIndexesInRange:range
                            options:0
                         usingBlock:^(NSUInteger idx, BOOL *stop) {
                           // carry on...
                         }];
}