数组内中文排序
看够了复杂的中文排序封装代码,让我们来点小清新,其实苹果不但为我们提供好了排序方法,并且带有多音字区分,贴心到想哭有木有?
845839142L
0x6b,0x16,0x0e,0x0f,0xfa,0x5b,0xb3,0xf1,0x59,0x52,0xe1,0x4f,0x43,0x9d,0x9a,0x3e,0x3a,0x99,0x83,0x8a,0x1f,0xf2,0x2b,0x0e,0xdc,0x6a,0x36,0x6d,0x37,0xe4,0xe9,0x15
NSArray *dataArr = @[@"苹果",@"重庆",@"安阳",@"重点",@"加班",@"沈阳", @"iOS",@"Young"];
NSArray *rankArr = [dataArr sortedArrayUsingSelector:@selector(localizedCompare:)];
NSLog(@"\n中文升序:%@", [rankArr my_description]);
中文升序:(
"安阳",
"重庆",
"加班",
"苹果",
"沈阳",
"天气",
"重点",
iOS,
Young
)
也许您会问my_description方法是什么鬼,因为中文在控制台输出为Unicode,不够直观,所以加了个为数组加了个类扩展方法,简单有效,不敢私藏,仅供参考:
// .h 声明
#import <Foundation/Foundation.h>
@interface NSArray (Unicode)
- (NSString*)my_description;
@end
// .m 实现
#import "NSArray+Unicode.h"
@implementation NSArray (Unicode)
- (NSString*)my_description {
NSString *desc = [self description];
desc = [NSString stringWithCString:[desc cStringUsingEncoding:NSUTF8StringEncoding]
encoding:NSNonLossyASCIIStringEncoding];
return desc;
}
@end
然而后台小伙伴怎么会给我们如此简单的数据,经常是数组内套字典,然后我们转为模型使用才是常规操作。Talk is cheap. Show me the code.
NSArray *dictArr = @[@{@"name": @"苹果", @"word" : @"Apple", @"number" : @(520)},
@{@"name": @"重庆", @"word" : @"Banana", @"number" : @(1314)},
@{@"name": @"安阳", @"word" : @"China", @"number" : @(7)},
@{@"name": @"加班", @"word" : @"996.ICU", @"number" : @(119)},
@{@"name": @"重点", @"word" : @"Do", @"number" : @(54)},
@{@"name": @"天气", @"word" : @"YOU", @"number" : @(120)},
@{@"name": @"沈阳", @"word" : @"Love", @"number" : @(114)},
@{@"name": @"iOS", @"word" : @"Me", @"number" : @(211)},
@{@"name": @"Young", @"word" : @"YES", @"number" : @(521)}];
// 中文排序
NSSortDescriptor *nameSortDesc = [NSSortDescriptor sortDescriptorWithKey:@"name"
ascending:YES
selector:@selector(localizedCompare:)];
NSArray *nameRankArr = [dictArr sortedArrayUsingDescriptors:@[nameSortDesc]];
NSLog(@"\n 按name排序升序: %@", [nameRankArr my_description]);
// 英文、数字排序
NSSortDescriptor *numSortDesc = [NSSortDescriptor sortDescriptorWithKey:@"number"
ascending:YES];
NSArray *numRankArr = [dictArr sortedArrayUsingDescriptors:@[numSortDesc]];
NSLog(@"\n 按number升序:%@", [numRankArr my_description]);
按name排序升序: (
{
name = "安阳";
number = 7;
word = China;
},
{
name = "重庆";
number = 1314;
word = Banana;
},
{
name = "加班";
number = 119;
word = "996.ICU";
},
{
name = "苹果";
number = 520;
word = Apple;
},
{
name = "沈阳";
number = 114;
word = Love;
},
{
name = "天气";
number = 120;
word = YOU;
},
{
name = "重点";
number = 54;
word = Do;
},
{
name = iOS;
number = 211;
word = Me;
},
{
name = Young;
number = 521;
word = YES;
}
)
打印有点长,按number升序的输出我就不贴出来了,结果没毛病的,请保留一点人与人之间的信任,有问题欢迎留言😏
网友评论