iOS 中文排序

2018-06-01  本文已影响118人  突刺刺

需求:中文排序

方法一

- (NSArray *)charactersOrder1:(NSArray*)array
{
    NSSortDescriptor * sort = [NSSortDescriptor sortDescriptorWithKey:@"pinyin" ascending:YES];
    NSArray *newArray = [NSArray arrayWithObject:sort];
    return [array sortedArrayUsingDescriptors: newArray];
}

方法二

- (NSArray *)charactersOrder2:(NSArray*)array
{
     NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch|NSNumericSearch|NSWidthInsensitiveSearch|NSForcedOrderingSearch;
     NSComparator sort = ^(NSString *obj1,NSString *obj2){
     NSString *pinyin1 = [obj1 pinyin];/*获取obj1的首字母*/
     NSString *pinyin2 = [obj2 pinyin];/*获取obj2的首字母*/
     NSRange range = NSMakeRange(0,pinyin1.length);
     return [pinyin1 compare:pinyin2 options:comparisonOptions range:range];
     };
     return [self sortedArrayUsingComparator:sort];
}

/*获取中文的首字母*/
- (NSString *)pinyin
{
    NSMutableString *source = [self mutableCopy];
    CFStringTransform((CFMutableStringRef)source, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)source, NULL, kCFStringTransformStripDiacritics, NO);//这一行是去声调的
    return source;
}

方法三 记录,有疑问

- (NSArray *)charactersOrder2:(NSArray*)array
{
    return [array sortedArrayUsingSelector:@selector(localizedCompare:)];
}

对比三种方法的结果

- (void)test
{
     NSArray *city = @[@"北京", @"广州",@"深圳",@"上海", @"重庆"];
    NSArray *city1  = [self charactersOrder1: city];//@"方法1"
    NSArray *city2  = [self charactersOrder2: city];//@"方法2"
    NSArray *city3  = [self charactersOrder3: city];//@"方法3"
    NSLog(@"city1 %@",city1);
    NSLog(@"city2 %@",city2);
    NSLog(@"city3 %@",city3);

}

打印

 city1 = (
    北京,
    重庆,
    广州,
    上海,
    深圳,
)
 city2 = (
    北京,
    重庆,
    广州,
    上海,
    深圳,
)
 city3 = (
    上海,
    北京,
    广州,
    深圳,
    重庆,
)

区别

上一篇下一篇

猜你喜欢

热点阅读