拼音列表排序

数据格式

"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 *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;
}];

你可能感兴趣的:(拼音列表排序)