views:

329

answers:

1

Hey there,

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

+4  A: 

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.

Peter Hosey
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
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.
Ahruman
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.
Peter Hosey