1
2
3 // 按首字母分组排序数组
4
5 -(NSMutableArray *)sortObjectsAccordingToInitialWith:(NSArray *)arr {
6
7
8
9 // 初始化UILocalizedIndexedCollation
10
11 UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
12
13
14
15 //得出collation索引的数量,这里是27个(26个字母和1个#)
16
17 NSInteger sectionTitlesCount = [[collation sectionTitles] count];
18
19 //初始化一个数组newSectionsArray用来存放最终的数据,我们最终要得到的数据模型应该形如@[@[以A开头的数据数组], @[以B开头的数据数组], @[以C开头的数据数组], ... @[以#(其它)开头的数据数组]]
20
21 NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
22
23
24
25 //初始化27个空数组加入newSectionsArray
26
27 for (NSInteger index = 0; index < sectionTitlesCount; index++) {
28
29 NSMutableArray *array = [[NSMutableArray alloc] init];
30
31 }
32
33
34
35 //将每个名字分到某个section下
36
37 for (ContactsUserModel *userModel in _aryUser ){
38
39 //获取name属性的值所在的位置,比如"林丹",首字母是L,在A~Z中排第11(第一位是0),sectionNumber就为11
40
41 // trueName model 对应的属性名
42
43
44
45 NSInteger sectionNumber = [collation sectionForObject:userModel collationStringSelector:@selector(trueName)];
46
47 //把name为“林丹”的p加入newSectionsArray中的第11个数组中去
48
49 NSMutableArray *sectionNames = newSectionsArray[sectionNumber];
50
51 [sectionNames addObject:userModel];
52
53
54
55
56
57 NSLog(@"sectionNames===%@",sectionNames);
58
59
60
61 }
62
63
64
65 NSLog(@"newSectionsArray==%@",newSectionsArray);
66
67
68
69
70
71 //对每个section中的数组按照name属性排序
72
73 for (NSInteger index = 0; index < sectionTitlesCount; index++) {
74
75 NSMutableArray *personArrayForSection = newSectionsArray[index];
76
77 NSArray *sortedPersonArrayForSection = [collation sortedArrayFromArray:personArrayForSection collationStringSelector:@selector(name)];
78
79 newSectionsArray[index] = sortedPersonArrayForSection;
80
81 }
82
83 NSLog(@"newSectionsArray==%@",newSectionsArray);
84
85
86
87 // //删除空的数组
88
89 NSMutableArray *finalArr = [NSMutableArray new];
90
91 _sectionTitles =[NSMutableArray array];
92
93 [_sectionTitles addObject:@"部门"];
94
95
96
97
98
99 for (NSInteger index = 0; index < sectionTitlesCount; index++) {
100
101
102
103 if (((NSMutableArray *)(newSectionsArray[index])).count != 0) {
104
105 [finalArr addObject:newSectionsArray[index]];
106
107 [self.sectionTitles addObject: [[collation sectionTitles] objectAtIndex:index]];
108
109
110
111
112
113 }
114
115 }
116
117
118
119 return finalArr;//删除没有值的数组
120
121
122
123
124
125 // return newSectionsArray;
126
127
128
129 }
130
131
132
134
135 #pragma mark SectionTitles
136
137 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
138
139 {
140
141 return self.sectionTitles[section];
142
143 }
144
145
146
147 - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
148
149 {
150
151 return self.sectionTitles;
152
153 }