0

I have a mutable array that contains mutable dictionaries with strings for the keys latitude, longitude and id. Some of the latitude and longitude values are the same and I want to remove the duplicates from the array so I only have one object per location.

I can enumerate my array and using a second enumeration review each object to find objects that have different ids, but the same latitude and longitude, but if I try to remove the object, I'm muting the array during enumeration.

Is there any way to remove objects from an array while enumerating so I only enumerate the current set of objects as the array is updated?

Hope this question makes sense.

Thanks, Howie

2 Answers 2

5

Count up an index variable as you enumerate. When you come upon a dictionary you're interested in removing, add its index to a mutable index set. Then, when you finish enumerating, send the array a removeObjectsAtIndexes: message, passing the index set.

The other way would be to build up a second array, then send the first array a setArray: message, passing the second array—or release the first, retain the second, and set the second as the new first.

On an unrelated note, you might consider replacing the dictionaries with model objects. It tends to make for cleaner code.

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

3 Comments

Thanks for the advice - I actually tried something like this, but there's a problem. If I'm on index 3 and I find it has the same location as index 4, I would add index 4 to the array "to be removed". When I loop around for the next iteration I want the object at index 4 to be skipped since I already know it's a duplicate. Is there any way to remove objects from the original array as I enumerate or by using some other looping method?
Ward, neither of the methods Peter suggests has the problem you describe. Nevertheless, there is a simple way to avoid it if you want to do things manually: iterate over the objects to be deleted from the highest index to the lowest.
Ward: No, you cannot mutate the array while you enumerate it. That will cause a Cocoa exception. You must either mutate it or replace it after the loop, or loop on a copy. I recommend the removeObjectsAtIndexes: solution.
2

Actually you can. You need to go from top index to 0. Try this:

for (int i = [mutableArray count] -1; i >=0; i--) {
    id yourObject = [mutableArray objectAtIndex: i];
    BOOL needToDelete;
    // place you conditions here...

    if (needToDelete) {
        [mutableArray removeObject: yourObject];
    }
}

2 Comments

Can i use reverseObjectEnumerator for it?
Yes, you can. I've just tested it with reverseObjectEnumerator and it works fine.

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.