iOS 开发 排序问题 (好友列表,按字母排序)

iOS 开发 排序问题 (好友列表,按字母排序)

一、预备工作
①好友数据模型展示
FriendModel

@property(nonatomic,copy)NSString *photo;
@property(nonatomic,copy)NSString *userName;
@property(nonatomic,copy)NSString *userId;
@property(nonatomic,copy)NSString *phoneNO;

我们用userName的首字母排序;
② 存放model的数组 dataSource
③存放所有首字母的数组 lettersArray
④存放首字母对应字典, nameDic 字典中内容为该字母下的model数组

二、 下面是排序方法

- (void)handleLettersArray
{
    NSMutableDictionary *tempDic = [[NSMutableDictionary alloc]init];

    for(FriendModel *friends  in dataSource)//①、②
    {
        HanyuPinyinOutputFormat *formatter =  [[HanyuPinyinOutputFormat alloc] init];
        formatter.caseType = CaseTypeLowercase;
        formatter.vCharType = VCharTypeWithV;
        formatter.toneType = ToneTypeWithoutTone;

        NSString *outputPinyin=[PinyinHelper toHanyuPinyinStringWithNSString:friends.userName withHanyuPinyinOutputFormat:formatter withNSString:@""];
        NSLog(@"%@",[[outputPinyin substringToIndex:1] uppercaseString]);
        [tempDic setObject:friends forKey:[[outputPinyin substringToIndex:1] uppercaseString]];
    }

    self.lettersArray = tempDic.allKeys;//③

    for (NSString *letter in self.lettersArray) {
        NSLog(@"letter==%@",letter);
        NSMutableArray *tempArry = [[NSMutableArray alloc] init];

        for (NSInteger i = 0; i.count; i++) {
            FriendModel *friends = dataSource[i];
            NSLog(@"name = %@",friends.userName);

            HanyuPinyinOutputFormat *formatter =  [[HanyuPinyinOutputFormat alloc] init];
            formatter.caseType = CaseTypeUppercase;
            formatter.vCharType = VCharTypeWithV;
            formatter.toneType = ToneTypeWithoutTone;


            NSString *outputPinyin=[PinyinHelper toHanyuPinyinStringWithNSString:friends.userName withHanyuPinyinOutputFormat:formatter withNSString:@""];
            NSLog(@"%@",[[outputPinyin substringToIndex:1] uppercaseString]);
            if ([letter isEqualToString:[[outputPinyin substringToIndex:1] uppercaseString]]) {
                [tempArry addObject:friends];

            }

        }
        [self.nameDic setObject:tempArry forKey:letter];// ④
//        NSLog(@"tempArry==%@",tempArry);
    }

    self.lettersArray = tempDic.allKeys;
//    NSLog(@"%@",self.lettersArray);

    NSComparator cmptr = ^(id obj1, id obj2){
        if ([obj1 characterAtIndex:0] > [obj2 characterAtIndex:0]) {
            return (NSComparisonResult)NSOrderedDescending;
        }

        if ([obj1 characterAtIndex:0] < [obj2 characterAtIndex:0]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    };

    self.lettersArray = [[NSMutableArray alloc]initWithArray:[self.lettersArray sortedArrayUsingComparator:cmptr]];
    NSLog(@"%@",self.lettersArray);
}

三、用法
做tableView时,用letterArray确定分组数,取出key,用key从nameDic中取出该组的model。

你可能感兴趣的:(iOS-开发)