19

我有这种情况

array = [[NSMutableArray alloc] initWithCapacity:4]; //in viewDidLoad

if (index == 0){
    [array insertObject:object atIndex:0];
}

if (index == 1){
    [array insertObject:object atIndex:1];
}

if (index == 2){
    [array insertObject:object atIndex:2];
}

if (index == 3){
    [array insertObject:object atIndex:3];
}

但是如果我按顺序插入对象就可以了,相反,如果我按以下顺序填充数组:0和3之后,它就不能正常工作,为什么???

4

4 回答 4

55

NSMutableArray即使它的容量为 4 ,您也不能在索引 3 处插入对象。可变数组的可用“单元”与其中的对象一样多。如果你想在可变数组中有“空单元格”,你应该使用[NSNull null]对象。这是一个特殊的存根对象,意味着这里没有数据。

NSMutableArray *array = [[NSMutableArray alloc] init];

for (NSInteger i = 0; i < 4; ++i)
{
     [array addObject:[NSNull null]];
}

[array replaceObjectAtIndex:0 withObject:object];
[array replaceObjectAtIndex:3 withObject:object];
于 2011-04-22T11:16:27.170 回答
11

In C style int a[10] creates an array of size 10 and you can access any index from 0 to 9 in any order. But this is not the case with initWithCapacity or arrayWithCapacity. It is just a hint that the underlying system can use to improve performance. This means you can not insert out of order. If you have a mutable array of size n then you can insert only from index 0 to n, 0 to n-1 is for existing positions and n for inserting at end position. So 0, 1, 2, 3 is valid. But 0, 3 or 1,2 order is not valid.

于 2011-04-22T11:18:28.140 回答
0

You cann't insert at any random index, if you want to do this then first initialize your array with null objects then call replaceObjectAtIndex.

于 2011-04-22T11:20:58.077 回答
-3

您不能首先插入,例如在索引 0 处,然后在索引 2 处,您必须逐步插入词干插入到 0,1,2,3,4,5 .....,n 你想做什么???你有什么问题 ???

您可以尝试创建一个数组,然后用零项初始化它,然后插入它!!!我认为它会工作!

于 2011-04-22T11:13:10.647 回答