병음 목록 정렬

1737 단어

데이터 형식

"data" : [
    {
      "brandId" : "13",
      "pinyin" : "A",
      "brandName" : " "
    },
    {
      "brandId" : "44",
      "pinyin" : "A",
      "brandName" : " · "
    },
    {
      "brandId" : "45",
      "pinyin" : "A",
      "brandName" : " "
    }
 ]

모델 객체

@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;
}];

좋은 웹페이지 즐겨찾기