IOS: NSMutableArray initWithCapacity IOS: NSMutableArray initWithCapacity xcode xcode

IOS: NSMutableArray initWithCapacity


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.