-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathJLIndexedList.m
99 lines (74 loc) · 2.71 KB
/
JLIndexedList.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//
// JLIndexedList.m
// Additions
//
// Created by jlopez on 2/13/10.
// Copyright 2010 JLA. All rights reserved.
//
#import "JLIndexedList.h"
@implementation JLIndexedList
@synthesize indexTitles;
@synthesize sections;
+ (id)indexedListWithArray:(NSArray *)array labelSelector:(SEL)labelSelector index:(BOOL)flag {
return [[[self alloc] initWithArray:array labelSelector:labelSelector index:flag] autorelease];
}
+ (id)indexedListWithValues:(NSArray *)values header:(NSString *)header {
return [[[self alloc] initWithValues:values header:header] autorelease];
}
NSInteger comparingFunction(id v1, id v2, void *ctx) {
SEL selector = (SEL)ctx;
return [[v1 performSelector:selector] compare:[v2 performSelector:selector]];
}
- (id)initWithArray:(NSArray *)array labelSelector:(SEL)selector index:(BOOL)flag {
if (self = [super init]) {
labelSelector = selector;
NSMutableArray *sections_ = [NSMutableArray arrayWithCapacity:26];
NSMutableArray *indexTitles_ = flag ? [NSMutableArray arrayWithCapacity:26] : nil;
NSMutableArray *section = nil;
unichar currentLetter = 0;
for (id value in [array sortedArrayUsingFunction:comparingFunction context:labelSelector]) {
NSString *label = [value performSelector:labelSelector];
unichar letter = [label characterAtIndex:0];
if ((!flag && currentLetter == 0) || (flag && currentLetter != letter)) {
if (section)
[sections_ addObject:section];
section = [NSMutableArray arrayWithCapacity:4];
currentLetter = letter;
[indexTitles_ addObject:[label substringToIndex:1]];
}
[section addObject:value];
}
if (section)
[sections_ addObject:section];
sections = [sections_ retain];
indexTitles = [indexTitles_ retain];
}
return self;
}
- (id)initWithValues:(NSArray *)values header:(NSString *)header {
if (self = [super init]) {
indexTitles = [[NSArray arrayWithObject:header] retain];
sections = [[NSArray arrayWithObject:values] retain];
labelSelector = @selector(description);
}
return self;
}
- (NSString *)labelAtIndexPath:(NSIndexPath *)indexPath {
return [[self valueAtIndexPath:indexPath] performSelector:labelSelector];
}
- (NSIndexPath *)indexPathForValue:(id)value {
if (value == nil)
return nil;
for (int sec = 0; sec < [sections count]; ++sec) {
NSArray *section = [sections objectAtIndex:sec];
for (int row = 0; row < [section count]; ++row) {
if ([value isEqual:[section objectAtIndex:row]])
return [NSIndexPath indexPathForRow:row inSection:sec];
}
}
return nil;
}
- (id)valueAtIndexPath:(NSIndexPath *)indexPath {
return [[sections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
}
@end