有没有办法让NSMutableArray允许你在数组中有"漏洞",只有部分数组被填充而不是有连续的项目?
我想创建初始数组,并在数组的开头填充一些元素.一段时间之后,我想插入9个新项目,而不是在我当前的最后一个项目之后,但是在阵列中间的某个点,因此在数组列表的某些部分留下了一个洞.
我以为我可以这样做,但我收到错误:
NSRangeException', reason: '***
-[NSMutableArray insertObject:atIndex:]: index 28 beyond bounds [0 .. 5]'
Run Code Online (Sandbox Code Playgroud)
码:
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];
}
Run Code Online (Sandbox Code Playgroud)
我不想在孔中插入"空白"项,因为当我可以在数组中保存数百个对象时会占用内存.
我需要某种"稀疏"数组数据结构.
| 归档时间: |
|
| 查看次数: |
8752 次 |
| 最近记录: |