美文网首页
拼音列表排序

拼音列表排序

作者: cocoaroger | 来源:发表于2018-07-31 09:39 被阅读6次

数据格式

"data" : [
    {
      "brandId" : "13",
      "pinyin" : "A",
      "brandName" : "奥迪"
    },
    {
      "brandId" : "44",
      "pinyin" : "A",
      "brandName" : "阿斯顿·马丁"
    },
    {
      "brandId" : "45",
      "pinyin" : "A",
      "brandName" : "奥克斯"
    }
 ]

Model对象

@interface LTBrandItem : NSObject

@property (assign, nonatomic) NSInteger brandId;
@property (copy, nonatomic) NSString *pinyin;
@property (copy, nonatomic) NSString *brandName;

@end

@interface LTBrandCellModel : NSObject

@property (copy, nonatomic) NSString *letter;

@property (strong, nonatomic) NSMutableArray<LTBrandItem*> *list;

@end

排序代码

NSArray *list = response.data;
NSMutableArray *sections = [NSMutableArray array];
for (NSDictionary *dict in list) {
    LTBrandItem *item = [LTBrandItem mj_objectWithKeyValues:dict];
    BOOL hasSection = NO; // 是否已经有section
    for (LTBrandCellModel *section in sections) {
        if ([section.letter isEqualToString:item.pinyin]) {
            [section.list addObject:item];
            hasSection = YES;
            break;
        }
    }
    if (!hasSection) {
        LTBrandCellModel *section = [LTBrandCellModel new];
        section.letter = item.pinyin;
        section.list = [NSMutableArray array];
        [section.list addObject:item];
        [sections addObject:section];
    }
}
[sections sortUsingComparator:^NSComparisonResult(LTBrandItem *obj1, LTBrandItem *obj2) {
    return obj1.pinyin > obj2.pinyin;
}];

相关文章

网友评论

      本文标题:拼音列表排序

      本文链接:https://www.haomeiwen.com/subject/ncjcvftx.html