Ward
Ward

Reputation: 3318

Cocoa - Enumerate mutable array, removing objects

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

Upvotes: 0

Views: 1024

Answers (2)

Vitali Usau
Vitali Usau

Reputation: 209

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];
    }
}

Upvotes: 2

Peter Hosey
Peter Hosey

Reputation: 96363

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.

Upvotes: 5

Related Questions