Search code examples
objective-cnsarrayunique

Removing duplicates from array based on a property in Objective-C


I have an array with custom objects. Each array item has a field named "name". Now I want to remove duplicate entries based on this name value.

How should I go about achieving this?


Solution

  • You might have to actually write this filtering method yourself:

    @interface NSArray (CustomFiltering)
    @end
    
    @implementation NSArray (CustomFiltering) 
    
    - (NSArray *) filterObjectsByKey:(NSString *) key {
       NSMutableSet *tempValues = [[NSMutableSet alloc] init];
       NSMutableArray *ret = [NSMutableArray array];
       for(id obj in self) {
           if(! [tempValues containsObject:[obj valueForKey:key]]) {
                [tempValues addObject:[obj valueForKey:key]];
                [ret addObject:obj];
           }
       }
       [tempValues release];
       return ret;
    }
    
    @end