5
有没有办法让NSMutableArray允许您在数组中只有部分数组填充而不是连续项的数组中有“空洞”?NSMutableArray的insertObjects:atIndexes和索引超出界限
我想创建初始数组,其中一些元素填充在数组的开头。一段时间后,我想插入9个新的项目,不是在我目前的最后一个之后,而是在数组中间的某个点上,因此在数组列表的某些部分留下了一个空洞。
我想我可以做到这一点,但我得到的错误:
NSRangeException', reason: '***
-[NSMutableArray insertObject:atIndex:]: index 28 beyond bounds [0 .. 5]'
代码:
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];
}
我不想插入“空白”中的孔,因为这会项目当我可以在阵列中容纳几百个对象时占用内存。
我需要某种“稀疏”数组数据结构。