系统方法解读

IOS按照拼音首字母排序

2016-09-03  本文已影响3241人  蜗牛1992
/*按照拼音首字母排序*/
-(NSMutableArray*) SortPinYing:(NSMutableArray*)pFriendListArray
{
    
    NSMutableArray* pAllArray = [[NSMutableArray alloc] init];
    for(char sz = 'A'; sz <= 'Z'; ++sz)
    {
        NSMutableArray* pArray = [[NSMutableArray alloc] init];
        for(int i = 0;i < pFriendListArray.count; ++i)
        {
            UserFriendItem* pItem = (UserFriendItem*)[pFriendListArray objectAtIndex:i];
            
            NSString* pPinYin = [CommonUtil FirstCharactor:pItem->pstrName];
            if(NSOrderedSame == [[NSString stringWithFormat:@"%c", sz] compare:pPinYin])
            {
                [pArray addObject:pItem];
            }
        }
        
        while(true)
        {
            int i = 0;
            for(;i < pFriendListArray.count; ++i)
            {
                UserFriendItem* pItem = (UserFriendItem*)[pFriendListArray objectAtIndex:i];
                
                NSString* pPinYin = [CommonUtil FirstCharactor:pItem->pstrName];
                if(NSOrderedSame == [[NSString stringWithFormat:@"%c", sz] compare:pPinYin])
                {
                    [pFriendListArray removeObjectAtIndex:i];
                    break;
                }
            }
            
            if(i == pFriendListArray.count)
            {
                if(pArray.count > 0)
                {
                    UserFriendItem* pItem = [[UserFriendItem alloc] init];
                    pItem->pstrId = @"-1";
                    pItem->pstrName = [NSString stringWithFormat:@"%c", sz];
                    
                    [pAllArray addObject:pItem];
                    [pAllArray addObjectsFromArray:pArray];
                }
                
                break;
            }
        }
    }
    
    if (pFriendListArray.count != 0) {
        UserFriendItem* pItem = [[UserFriendItem alloc] init];
        pItem->pstrId = @"-1";
        pItem->pstrName = @"#";
        [pAllArray addObject:pItem];
        [pAllArray addObjectsFromArray:pFriendListArray];
    }
    return pAllArray;
    
}

//CommonUtil里面的类方法:
//获取拼音首字母(传入汉字字符串, 返回大写拼音首字母)
+(NSString *)FirstCharactor:(NSString *)pString
{
    //转成了可变字符串
    NSMutableString *pStr = [NSMutableString stringWithString:pString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)pStr,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)pStr,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pPinYin = [pStr capitalizedString];
    //获取并返回首字母
    return [pPinYin substringToIndex:1];
}
上一篇 下一篇

猜你喜欢

热点阅读