indexSetWithIndexesInRange is not doing what expected
Asked Answered
O

1

5

I want to select some objects from an array. Therefore I'm using begin and end indexes of my selection.

NSLog(@"start:%d\nend:%d", startIndex, endIndex);
NSIndexSet *myIndexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(startIndex, endIndex)];
NSLog(@"%d", [myIndexes lastIndex]);

The first NSLog gives me

startIndex:49
endIndex:67

The second NSLog gives me

115

Why do I have 115 as highest number? It should be 67. Of course the app crashes:

Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSArray objectsAtIndexes:]: index 115 beyond bounds [0 .. 96]'

What I'm doing wrong?

Overbearing answered 25/10, 2010 at 20:18 Comment(0)
F
16

NSRange's members are location and length, not start and end. This means you need to create your NSRange struct like this:

NSMakeRange(startIndex, endIndex - startIndex);
Fat answered 25/10, 2010 at 20:23 Comment(1)
This saved me lots of time and energy!Bonnett

© 2022 - 2024 — McMap. All rights reserved.