类似微信通讯录界面的排序方法及中文转拼音的方法

最近做一个类似微信的通讯录列表,因为本人也算个新手,然后呢,就遇到点问题。难点在对昵称的排序上,顺带着也就找了找中文转拼音的方法。

废话不多说,直接贴代码吧

1、首先要对昵称字符串进行中文转拼音,这个比较简单,写到NSString分类里面就行。

- (NSString *)pinyin;
{
    NSMutableString *str = [self mutableCopy];
    CFStringTransform(( CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    
   return [str stringByReplacingOccurrencesOfString:@" " withString:@""];//顺带去除字符串前面的空格    }

 2、对昵称字符串数组进行分组,按a--z--#的顺序,相同首字母的保存在同一个数组中。

+ (NSMutableArray *) getNameCellArrayBy:(NSMutableArray *)array{
    NSMutableArray *ans = [[NSMutableArray alloc] init];
    
    NSArray *serializeArray = [(NSArray *)array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {//排序
        int i;
        NSString *strA = ((NSString *)obj1).pinyin;
        NSString *strB = ((NSString *)obj2).pinyin;
        for (i = 0; i < strA.length && i < strB.length; i ++) {
            char a = [strA characterAtIndex:i];
            char b = [strB characterAtIndex:i];
            if (a > b) {
                return (NSComparisonResult)NSOrderedDescending;//上升
            }
            else if (a < b) {
                return (NSComparisonResult)NSOrderedAscending;//下降
            }
        }
        
        if (strA.length > strB.length) {
            return (NSComparisonResult)NSOrderedDescending;
        }else if (strA.length < strB.length){
            return (NSComparisonResult)NSOrderedAscending;
        }else{
            return (NSComparisonResult)NSOrderedSame;
        }
    }];
    
    char lastC = '1';
    NSMutableArray *data;
    NSMutableArray *oth = [[NSMutableArray alloc] init];
    for (NSString *user in serializeArray) {
        char c = [user.pinyin characterAtIndex:0];
        if (!isalpha(c)) {
            [oth addObject:user];
        }
        else if (c != lastC){
            lastC = c;
            if (data && data.count > 0) {
                [ans addObject:data];
            }
            
            data = [[NSMutableArray alloc] init];
            [data addObject:user];
        }
        else {
            [data addObject:user];
        }
    }
    if (data && data.count > 0) {
        [ans addObject:data];
    }
    if (oth.count > 0) {
        [ans addObject:oth];
    }
    return ans;
}

 3、获取排号顺序的昵称数组的首字母。

+ (NSMutableArray *)getNameSectionArrayBy:(NSMutableArray *)array{
    NSMutableArray *section = [[NSMutableArray alloc] init];
for (NSArray *item in array) { NSString *user = [item objectAtIndex:0]; char c = [user.pinyin characterAtIndex:0]; if (!isalpha(c)) { c = '#'; } [section addObject:[NSString stringWithFormat:@"%c", toupper(c)]]; } return section; }

 完结。。。新手谨以此记录,防止以后忘记找不到了。

posted on 2016-06-17 11:48  HL丶  阅读(1527)  评论(0编辑  收藏  举报

导航