NSMutableArray
is not a sparse array; it does not allow empty slots that can be filled in later. initWithCapacity:
just hints to the array that it will be filled to a certain amount; it isn't generally necessary in practice and, unless you know exactly how many items you are going to shove in the array, don't bother calling it (just use init
).
A mutable array will quite efficiently grow in size as objects are added.
If you need a data structure that supports "holes", then either use something else or put a placeholder object in the slots that are supposed to be empty.
I.e. if you wanted an array with 10 slots, you might do:
NSMutableArray *a = [NSMutableArray array];
for(int i = 0; i<10; i++) [a addObject: [NSNull null]];
You can then check if the retrieved object isEqual: [NSNull null]
to know if the slot is empty or not. And you can use replaceObjectAtIndex:withObject:
to stick an object at a specific index.
Or you could use a different data structure; a dictionary with the indices as the keys would work, for example.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…