Skip to content

Instantly share code, notes, and snippets.

@mz2
Created March 21, 2010 23:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mz2/339644 to your computer and use it in GitHub Desktop.
Save mz2/339644 to your computer and use it in GitHub Desktop.
NSArray+UniqueObjects.h: get unique objects from an NSArray, whilst maintaining sort ordering
#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
// 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment