Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableArray - disable reindexing on remove

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.

like image 818
user1518183 Avatar asked May 02 '26 13:05

user1518183


1 Answers

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.

like image 76
Gabriele Petronella Avatar answered May 05 '26 05:05

Gabriele Petronella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!