1

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];
    }
}
1
  • Is this behaving inefficiently? i.e., when you profile your application, do you see large slowdowns in this code fragment? Commented Apr 12, 2009 at 6:48

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the tip. I will try to benchmark this and see if the new approach is any faster.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.