NSArray+UniqueObjects

Posted by matias Thu, 30 Jul 2009 19:22:00 GMT

Hello world! I've recently come across the situation where I want to get rid of duplicate values in an NSArray but maintain a specific sort order. After researching the Cocoa documentation I couldn't find a way to doing this with a single method call. So here's a category on NSArray that does exactly this! So if you ever come across the same problem of getting the unique members of an NSArray in a certain sorting order, the following code should help you out. Here's the header:
#import <Foundation/Foundation.h>


@interface NSArray (UniqueObjects)

-(NSArray*) uniqueObjects;

-(NSArray*) uniqueObjectsSortedUsingSelector: (SEL)comparator;

-(NSArray*) uniqueObjectsSortedUsingFunction: (NSInteger (*)(id, id, void *)) comparator  
                                     context: (id)context 
                                        hint: (id)hint;

-(NSArray*) uniqueObjectsSortedUsingFunction: (NSInteger (*)(id, id, void *)) comparator 
                                     context: (id)context;

-(NSArray*) uniqueObjectsSortedUsingSortDescriptors: (NSArray*) sortDescs;

@end

... and the implementation:
#import "NSArray+UniqueObjects.h"


@implementation NSArray (UniqueObjects)

-(NSArray*) uniqueObjects {
    NSSet *set = [[NSSet alloc] initWithArray: self];
    NSArray *vals = [set allObjects];
    [set release];
    return vals;
}


-(NSArray*) uniqueObjectsSortedUsingSelector: (SEL)comparator {
    NSSet *set = 
        [[NSSet alloc] initWithArray: self];
    NSArray *vals = 
        [[set allObjects] sortedArrayUsingSelector: comparator];
    [set release];
    return vals;
}


-(NSArray*) 
uniqueObjectsSortedUsingFunction: 
(NSInteger (*)(id, id, void *)) comparator 
context: (id)context 

hint: (id)hint {
    NSSet *set = [[NSSet alloc] initWithArray: self];
    NSArray *vals = 
        [[set allObjects] sortedArrayUsingFunction: comparator
                                           context: context 
                                              hint: hint];
    [set release];
    return vals;
}


-(NSArray*) 
uniqueObjectsSortedUsingFunction: 
(NSInteger (*)(id, id, void *)) comparator 
context: (id)context {
    NSSet *set = [[NSSet alloc] initWithArray: self];

    NSArray *vals = [[set allObjects] 
    sortedArrayUsingFunction:comparator context:context];
    [set release];
    return vals;
}


-(NSArray*) 
uniqueObjectsSortedUsingSortDescriptors: (NSArray*) sortDescs 
{
    NSSet *set = [[NSSet alloc] initWithArray: self];
    NSArray *vals = 
        [[set allObjects] sortedArrayUsingDescriptors:sortDescs];
    [set release];
    return vals;
}


@end

enter>