NSMutableArray insertObjects: atIndexes and Out-of-bounds Index

Is there a way to force NSMutableArray to allow you to have “holes” in the array where only parts of the array are filled, not adjacent elements?

I want to create an initial array with some elements filled at the beginning of the array. After some time, I would like to insert 9 new elements, not immediately after my last, but at some point in the middle of the array, leaving a hole in the parts of the list of arrays there.

I thought I could do this, but we get the error:

NSRangeException', reason: '***
-[NSMutableArray insertObject:atIndex:]: index 28 beyond bounds [0 .. 5]'

the code:

NSMutableArray *targetArray = [NSMutableArray arrayWithCapacity:100];

- (void)fillInInitially {

// Add the first set of elements to the beginning of the array
    for (int i = 0; i < [initialData count]; ++i)
    {
        [targetArray insertObject:[initialData objectAtIndex:i] atIndex:i];
    }
}

- (void)fillInTheBlank:(NSArray *) additions {

    // Start adding at index position 28 and current array has 5 items
    NSRange range = NSMakeRange(28, [additions count]);     
    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];

    // Can't do this when I'm trying to add 9 new items at index 28
    // because of the error: index 28 beyond bounds [0 .. 5]
    [targetArray insertObjects:additions atIndexes:indexSet];
}

I did not want to insert “empty” elements into the holes, since it takes up memory, when I can contain several hundred objects in the array.

I need some sort of data structure with a sparse array.

+5
1

[NSNull null]. , , 100 [NSNull null] s.

+4

All Articles