UITableView 索引的设置
if (_indexCollation == nil) {
_indexCollation = [UILocalizedIndexedCollation currentCollation];
}
NSArray *localTracks = [NSArray array];
//查找本地音乐
NSEntityDescription * trEty = [NSEntityDescription entityForName:@"Track" inManagedObjectContext:ShareAppDelegate.managedObjectContext];
NSFetchRequest *frq = [[NSFetchRequest alloc]init];
[frq setEntity:trEty];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"beAdded == %@",[NSNumber numberWithBool:YES]];
[frq setPredicate:predicate];
localTracks =[ShareAppDelegate.managedObjectContext executeFetchRequest:frq error:nil];
//每个索引下的数组
NSMutableArray *newLocalTracks = [[NSMutableArray alloc] initWithCapacity:[[_indexCollation sectionTitles] count]];
for (int i = 0; i < [[_indexCollation sectionTitles] count]; i ++) {
NSMutableArray *array2 = [[NSMutableArray alloc] initWithCapacity:1];
[newLocalTracks addObject:array2];
}
for (Track *track in localTracks) {
//判断这个数据应该处于本地索引的那个序列下
NSInteger index = [_indexCollation sectionForObject:track collationStringSelector:@selector(trackTitle)];
NSMutableArray *array = [newLocalTracks objectAtIndex:index];
[array addObject:track];
__tracksCount ++;
}
//处理结果:将结果中统计数为0的结果对应的索引去掉。
for (int i = 0; i < [[_indexCollation sectionTitles] count]; i++) {
NSMutableArray *array = [newLocalTracks objectAtIndex:i];
if (array.count > 0) {
//获得排序结果
NSArray *sortedarray = [_indexCollation sortedArrayFromArray:array collationStringSelector:@selector(trackTitle)];
//替换原来数组
[newLocalTracks replaceObjectAtIndex:i withObject:sortedarray];
}
}
//删选没有内容的array 删除;加载数据到table,重新生成新的曲目数组及索引数组
NSMutableArray *newLocalTracks1 = [NSMutableArray array];
NSMutableArray *newIndexArray = [NSMutableArray array];
for (NSMutableArray *array in newLocalTracks)
{
if ([array count] > 0) {
[newLocalTracks1 addObject:array];
[newIndexArray addObject:[[_indexCollation sectionTitles] objectAtIndex:[newLocalTracks indexOfObject:array]]];
}
}
_tracksArray = [NSMutableArray arrayWithArray:newLocalTracks1];
_indexArray = [NSMutableArray arrayWithArray:newIndexArray];
dispatch_async(dispatch_get_main_queue(), ^{
[_table reloadData];
});
/* 返回索引数组 */
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return _indexArray;
}