使用CFStringTransform方便的进行中文名字的排序

#import <Foundation/Foundation.h>


@interface NSArray (chinese)


+(NSArray *)sortedArrayByChinese: (NSArray*) array;


@end


@interface Common_Manage : NSObject


+ (NSComparisonResult) CompareString: (NSString*) strSrc with:(NSString*) str2; 


@end



#import "Common_Manage.h"


@implementation Common_Manage


+(NSComparisonResult)CompareString:(NSString *)strSrc with:(NSString *)str2{

    CFStringRef cfstringSrc = CFStringCreateWithCString(NULL, strSrc.UTF8String, kCFStringEncodingUTF8);

    CFMutableStringRef src = CFStringCreateMutableCopy(NULL, 0, cfstringSrc);

    CFStringTransform(src, 0, kCFStringTransformToLatin, false);

    CFStringTransform(src, 0, kCFStringTransformStripCombiningMarks, false);

    

    CFStringRef cfstringto = CFStringCreateWithCString(NULL, str2.UTF8String, kCFStringEncodingUTF8);

    CFMutableStringRef srcto = CFStringCreateMutableCopy(NULL, 0, cfstringto);

    CFStringTransform(srcto, 0, kCFStringTransformToLatin, false);

    CFStringTransform(srcto, 0, kCFStringTransformStripCombiningMarks, false);

    

    CFComparisonResult result = CFStringCompare(src, srcto, kCFCompareCaseInsensitive);

    NSComparisonResult r = (NSComparisonResult)result;

    return r;

}


@end


@implementation NSArray (chinese)


+(NSArray*) sortedArrayByChinese: (NSArray*) array

{

    NSArray* ret = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

        NSComparisonResult ret = [Common_Manage CompareString:obj1 with:obj2];

        return ret;

    }];

    

    return ret;

}


@end



********************使用*********************

NSArray *array = [[NSArray alloc]initWithObjects:@"阿诶",@"啊啊",@"刘扬",@"刘江", nil];

    NSArray *sorted = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

        NSString *name1 = obj1;

        NSString *name2 = obj2;

        NSComparisonResult e = [Common_Manage CompareString:name1 with:name2];

        return e;

    }];

    for (int i = 0; i < [array count]; i++) {

        NSLog(@"%@",[sorted objectAtIndex:i]);

    }


备注:来源于http://blog.csdn.net/chiyun1/article/details/45042105



阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭