iOS:NSMutableArray initWithCapacity
我遇到这种情况
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 之后,它就不能正常工作,为什么???
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???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
即使它的容量为 4,您也无法在 NSMutableArray 中的索引 3 处插入对象。可变数组的可用“单元格”数量与其中的对象数量一样多。如果您想在可变数组中包含“空单元格”,您应该使用
[NSNull null]
对象。这是一个特殊的存根对象,意味着这里没有数据。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.在 C 风格中,
int a[10]
创建一个大小为 10 的数组,您可以按任意顺序访问从0
到9
的任何索引。但initWithCapacity
或arrayWithCapacity
的情况并非如此。这只是底层系统可以用来提高性能的一个提示。这意味着您不能乱序插入。如果您有一个大小为 n 的可变数组,则只能从索引0
插入到n
、0
到n-1< /code> 用于现有位置,
n
用于在结束位置插入。所以 0、1、2、3 是有效的。但 0、3 或 1,2 顺序无效。In C style
int a[10]
creates an array of size 10 and you can access any index from0
to9
in any order. But this is not the case withinitWithCapacity
orarrayWithCapacity
. 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 index0
ton
,0
ton-1
is for existing positions andn
for inserting at end position. So 0, 1, 2, 3 is valid. But 0, 3 or 1,2 order is not valid.您不能插入任何随机索引,如果您想这样做,请首先使用空对象初始化数组,然后调用replaceObjectAtIndex。
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.
你不能首先插入,例如在索引 0 处,然后在索引 2 处你必须逐步插入到 0,1,2,3,4,5.....,n 你想做什么???你有什么问题???
您可以尝试创建一个数组,然后用零个项目初始化它,然后插入它!我认为它会起作用!
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 ???
You can try to create an Array then init it with zero items and after that insert to it !!! I think it will work !!!