开发者

IOS: NSMutableArray initWithCapacity

I have this situation

array = [[NSMutableArray alloc] in开发者_高级运维itWithCapacity: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???


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 *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];


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.


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.


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 !!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜