Search code examples
nsrangeexception

NSMutableOrderedSet NSRangeException


I am getting a NSRangeException error and I can not find the error in this very basic bit of code. Can someone help correct my blindspot?

uint32_t offsetVal = 0;
int num = 100;
_offsetVals=[[NSMutableOrderedSet alloc]initWithCapacity:num+1];
for (int i=0; i<=num; i++) // note: there is 1 greater offset record than there is glyphs!
{
    CFDataGetBytes(tableData, CFRangeMake(offset,4),(UInt8*)&offsetVal);
    offsetVal=CFSwapInt32HostToBig(offsetVal);
    [_offsetVals insertObject:[NSNumber numberWithInt:offsetVal] atIndex:i];
    offset+=4;
}

Yet the app crashes with: 'NSRangeException', reason: '* -[__NSOrderedSetM setObject:atIndex:]: index 3 beyond bounds [0 .. 1]'


Solution

  • The issue was that a NSMutableOrderedSet regards the initial capacity as a hint rather than an instruction, so insert failed within a few because the system hadn't allocated the necessary space. From the manual (but not within the insertObject text):

    "NSMutableOrderedSet objects are not like C arrays. That is, even though you may specify a size when you create a mutable ordered set, the specified size is regarded as a “hint”; the actual size of the set is still 0. This means that you cannot insert an object at an index greater than the current count of an set. For example, if a set contains two objects, its size is 2, so you can add objects at indices 0, 1, or 2. Index 3 is illegal and out of bounds; if you try to add an object at index 3 (when the size of the array is 2), NSMutableOrderedSet raises an exception."