views:

1328

answers:

2

The best way to remove duplicate values (NSString) from NSMutableArray in Objective-C?

Is this the easiest and right way to do it?

uniquearray = [[NSSet setWithArray:yourarray] allObjects];
+5  A: 

Your NSSet approach is the best if you're not worried about the order of the objects, but then again, if you're not worried about the order, then why aren't you storing them in an NSSet to begin with?

If you are worried about the order, loop over a copy of the array:

NSArray *copy = [mutableArray copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator]) {
    if ([mutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
        [mutableArray removeObjectAtIndex:index];
    }
    index--;
}
[copy release];
Jim Puls
A: 

You might want to clarify whether you want to eliminate references to the exact same object, or also those which are distinct objects but have the same values for every field.

Amagrammer