IOS: NSMutableArray initWithCapacity

cyclingIsBetter picture cyclingIsBetter · Apr 22, 2011 · Viewed 31.7k times · Source

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

Answer

Zapko picture Zapko · Apr 22, 2011

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