-
Notifications
You must be signed in to change notification settings - Fork 41
/
NSCountedSet+Votes.m
72 lines (60 loc) · 1.53 KB
/
NSCountedSet+Votes.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#import "NSCountedSet+Votes.h"
#if 0
NSComparisonResult CompareCounts(id object1, id object2, void* countedSet) {
NSInteger count1 = [(NSCountedSet*)countedSet countForObject:object1] ;
NSInteger count2 = [(NSCountedSet*)countedSet countForObject:object2] ;
NSComparisonResult result ;
if (count1 < count2) {
result = NSOrderedDescending ;
}
else if (count1 > count2) {
result = NSOrderedAscending ;
}
else {
result = [object1 compare:object2] ;
}
return result ;
}
#endif
@implementation NSCountedSet (Votes)
#if 0
// This method seems to not work properly, then I decided that I didn't need it
- (NSArray*)arrayOrderedByCount {
NSArray* array = [self allObjects] ;
array = [array sortedArrayUsingFunction:CompareCounts
context:self] ;
return array ;
}
#endif
- (id)winner {
id winner = nil ;
NSInteger highestCount = 0 ;
for (id object in self) {
NSInteger count = [self countForObject:object] ;
if (count > highestCount) {
highestCount = count ;
winner = object ;
}
else if (count == highestCount) {
winner = nil ;
}
}
return winner ;
}
@end
@implementation NSDictionary (Subdictionaries)
- (NSCountedSet*)objectsInSubdictionariesForKey:(id)key
defaultObject:(id)defaultObject {
NSCountedSet* objects = [NSCountedSet set] ;
for (NSDictionary* subdictionary in [self allValues]) {
id object = [subdictionary objectForKey:key] ;
if (object) {
[objects addObject:object] ;
}
else if (defaultObject) {
[objects addObject:defaultObject] ;
}
}
return objects ;
}
@end