iOS中无序多数据按索引自动分类和排列

最近用美团购物的时候,发现了我们常用的tableview的索引情况,之前没怎么研究过索引,只知道是系统自带的方法,应该很简单的,然后动手去写了一下,倒是发现了一个问题:基本索引很简单,直接调系统的方法,然而涉及到多样化的数据时候,如何让数据自动分类以及排序就是个问题。然后动手呗,先百度找些资料,发现很多都说的不全面,而且杂乱无章,也看不明白,花了一下午时间,自己总算整理出来一些心得,并写了个demo,复用性蛮高的,现在贴下来。
新建User类,继承NSObject
User.h

-(id)init:(NSString*) _username name:(NSString*) _name;
@property (assign, readwrite, nonatomic) NSString *name;
@property (assign, readwrite, nonatomic) NSString *username;

User.m

@synthesize name,username;
-(id)init:(NSString*) _username name:(NSString*) _name {
    self = [super init];
    self.username = _username;
    self.name = _name;
    
    return self;
}

然后回到ViewController中,在.h文件中

@interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray *userArray; //数据源数组
@property (nonatomic, strong) NSMutableArray *sectionsArray;//存放section对应的userObjs数组数据

//UITableView索引搜索工具
@property (nonatomic, strong) UILocalizedIndexedCollation *collation;

ViewController.m中
重点:UILocalizedIndexedCollation类

//配置分组信息
- (void)configureSections {
   //初始化测试数据
    NSMutableArray *city = [[NSMutableArray alloc] init];
    _userArray = [NSMutableArray arrayWithObjects:@"北京",@"安徽",@"合肥",@"邯郸",@"蚌埠",@"上海",@"广州",@"西安",@"淮南",@"江西",@"武汉",@"广西",@"河北",@"俄罗斯",@"盐城",@"江苏",@"新疆",@"乌鲁木齐", nil]; 
//项目集成时候,也就把这里的_userArray数据源换一下,其他代码用我的不变即可,就可快速按照索引排序和分类
    for (int i = 0; i < _userArray.count; i++) {
        [city addObject:[[User alloc] init:_userArray[i] name:_userArray[i]]];
    }

    
    
    //获得当前UILocalizedIndexedCollation对象并且引用赋给collation,A-Z的数据
    self.collation = [UILocalizedIndexedCollation currentCollation];
    
    //获得索引数和section标题数
    NSInteger index, sectionTitlesCount = [[_collation sectionTitles] count];
    
    //临时数据,存放section对应的userObjs数组数据
    NSMutableArray *newSectionsArray = [[NSMutableArray alloc] initWithCapacity:sectionTitlesCount];
    
    //设置sections数组初始化:元素包含userObjs数据的空数据
    for (index = 0; index < sectionTitlesCount; index++) {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [newSectionsArray addObject:array];
    }
    
    //将用户数据进行分类,存储到对应的sesion数组中
    for (User *userObj in city) {
        
        //根据timezone的localename,获得对应的的section number
        NSInteger sectionNumber = [_collation sectionForObject:userObj collationStringSelector:@selector(username)];
        
        //获得section的数组
        NSMutableArray *sectionUserObjs = [newSectionsArray objectAtIndex:sectionNumber];
        
        //添加内容到section中
        [sectionUserObjs addObject:userObj];
    }
    
    //排序,对每个已经分类的数组中的数据进行排序,如果仅仅只是分类的话可以不用这步
    for (index = 0; index < sectionTitlesCount; index++) {
        
        NSMutableArray *userObjsArrayForSection = [newSectionsArray objectAtIndex:index];
        
        //获得排序结果
        NSArray *sortedUserObjsArrayForSection = [_collation sortedArrayFromArray:userObjsArrayForSection collationStringSelector:@selector(username)];
        
        //替换原来数组
        [newSectionsArray replaceObjectAtIndex:index withObject:sortedUserObjsArrayForSection];
    }
    self.sectionsArray = newSectionsArray;
}

delegate

#pragma mark -- delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // The number of sections is the same as the number of titles in the collation.
    return [[_collation sectionTitles] count];
    
}

//设置每个Section下面的cell数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    // The number of time zones in the section is the count of the array associated with the section in the sections array.
    NSArray *UserObjsInSection = [_sectionsArray objectAtIndex:section];
    
    return [UserObjsInSection count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    // Get the time zone from the array associated with the section index in the sections array.
    NSArray *userNameInSection = [_sectionsArray objectAtIndex:indexPath.section];
    
    // Configure the cell with the time zone's name.
    User *userObj = [userNameInSection objectAtIndex:indexPath.row];
    cell.textLabel.text = userObj.username;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

/*
 * 跟section有关的设定
 */
//设置section的Header
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSArray *UserObjsInSection = [_sectionsArray objectAtIndex:section];
    if(UserObjsInSection == nil || [UserObjsInSection count] <= 0) {
        return nil;
    }
    return [[_collation sectionTitles] objectAtIndex:section];
}
//设置索引标题
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return [_collation sectionIndexTitles];
}
//关联搜索
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return [_collation sectionForSectionIndexTitleAtIndex:index];
}

当然了,一开始我们还要创建tableview,这里就不写了,然后调用最上面那个重要方法configureSections(我都集成好了,读者可以直接对数据源做操作,即可),效果图如下:

Paste_Image.png

有的小伙伴想下载源码,博主最近正在研究github(之前没用过..),稍后会贴出地址。
如果你也喜欢的话,点个赞吧。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容