Question

I have an NSMutableArray with contents I want to replace with NSNull objects.

This is what I do:

NSMutableArray* nulls = [NSMutableArray array];

for (NSInteger i = 0; i < myIndexes.count; i++)
    [nulls addObject:[NSNull null]];

[stageMap replaceObjectsAtIndexes:myIndexes withObjects:nulls];

How can I do this more efficiently? Is there a way to enumerate an NSIndexSet, so I can replace the array content one by one?

Solved

Suggested method turns out to be 2x faster (avg 0.000565s vs 0.001210s):

if (myIndex.count > 0)
{
    NSInteger index = [myIndex firstIndex];

    for (NSInteger i = 0; i < myIndex.count; i++)
    {
        [stageMap replaceObjectAtIndex:index withObject:[NSNull null]];
        index = [myIndex indexGreaterThanIndex:index];
    }
}
Was it helpful?

Solution

You can use a for loop. Start with the first index, use indexGreaterThanIndex: to get the next index, and stop after you hit the last index.

Don't forget to account for an empty index set. Both the first and last index will be NSNotFound in that case. The easiest way is to test the index set's count; if it's zero, don't loop.

Also, what Jason Coco said about profiling. Don't worry too much about efficiency until your program works, and don't go optimizing things until you have run Shark (or Instruments, if that's your thing) and found exactly what is slow.

OTHER TIPS

I realise this is a very old question but I'm posting here in case anyone else finds this question you could use:

    [indexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
        NSLog(@"index: %d", idx);
        [objectArray replaceObjectAtIndex:idx 
                               withObject:newObject];
    }];

Which is a lot more succinct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top