Question

For example I have array:

NSMutableArray *array = [NSMutableArray arrayWithObjects:@1, @2, @3, nil];

Array looks like this:

0 => @1
1 => @2
2 => @3

Then I remove object at index 0

[array removeObjectAtIndex:0];

...and NSMutableArray automatically reindex array, so the array looks like this:

0 => @2
1 => @3

Question: Is it possible to disable the automatic array reindex on remove? Or is there a similar class to use instead of NSMutableArray? Thanks.

Was it helpful?

Solution

You cannot have discontinuous indexes, so your best chance is to use a placeholder object to replace the removed one. Something like

NSMutableArray *array = [NSMutableArray arrayWithObjects:@1, @2, @3, nil];
[array replaceObjectAtIndex:0 withObject:[NSNull null]];

Now you will have

0 => [NSNull null]
1 => @2
2 => @3

so the indexing of non-null objects is preserved.

OTHER TIPS

No, you cannot actually remove the object from a NSMutableArray and not have the index updated. But you could achieve the desired effect with a NSMutableDictionary (where you use a key (which can be a NSNumber) rather than the NSUInteger numeric index of a NSMutableArray).

NSMutableDictionary *dictionary = [@{@0 : @1,
                                     @1 : @2,
                                     @2 : @3} mutableCopy];

NSLog(@"before: %@", dictionary);

[dictionary removeObjectForKey:@0];

NSLog(@"after: %@", dictionary);

Yielding:

before: {
    0 = 1;
    1 = 2;
    2 = 3;
}
after: {
    1 = 2;
    2 = 3;
}

Thus, instead of:

NSNumber *number = [array objectAtIndex:0];

You'd use:

NSNumber *number = [dictionary objectForKey:@0];

Or, instead of:

NSNumber *number = array[0];

You'd use:

NSNumber *number = dictionary[@0];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top