NSMutableArray insert object at index

前端 未结 3 1732
盖世英雄少女心
盖世英雄少女心 2020-12-14 20:15

I have an empty mutable array. Is it possible to insert object at index 2 for example, while there\'s nothing at index 0 and 1? I mean to increase capacity dynamically or so

3条回答
  •  无人及你
    2020-12-14 21:01

    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.

提交回复
热议问题