IOS:NSMutableArray initWithCapacity
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5754798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IOS: NSMutableArray initWithCapacity
提问by cyclingIsBetter
I have this situation
我有这种情况
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];
}
but if I insert in order the object it's all ok, instead if I fill the array in this order: 0 and after 3, it don't work fine, why???
但是如果我按顺序插入对象就可以了,相反,如果我按以下顺序填充数组:0 和 3 之后,它不能正常工作,为什么???
回答by Zapko
You can't insert object at index 3 in NSMutableArray
even if it's capacity is 4. Mutable array has as many available "cells" as there are objects in it. If you want to have "empty cells" in a mutable array you should use [NSNull null]
objects. It's a special stub-objects that mean no-data-here.
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];
回答by taskinoor
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.
在C风格int a[10]
创建大小为10的数组,你可以访问任何指标0
,以9
任何顺序。但是对于initWithCapacity
or就不是这种情况arrayWithCapacity
。这只是底层系统可以用来提高性能的提示。这意味着您不能乱序插入。如果您有一个大小为 n 的可变数组,那么您只能从索引插入0
到n
,0
ton-1
用于现有位置和n
在结束位置插入。所以 0, 1, 2, 3 是有效的。但是 0、3 或 1,2 顺序无效。
回答by saadnib
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.
你不能在任何随机索引处插入,如果你想这样做,那么首先用空对象初始化你的数组,然后调用replaceObjectAtIndex。
回答by Viktor Apoyan
You can't insert at first for example at index 0 then at index 2 you must insert step by stem insert to 0,1,2,3,4,5.....,n What you want to do ??? What is your problem ???
你不能首先插入例如在索引 0 然后在索引 2 你必须逐步插入词干插入到 0,1,2,3,4,5.....,n 你想做什么???你有什么问题 ???
You can try to create an Array then init it with zero items and after that insert to it !!! I think it will work !!!
您可以尝试创建一个数组,然后用零项初始化它,然后插入它!!!我认为它会起作用!!!