Created
March 21, 2010 23:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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