我在排序方面遇到了问题。
数据就像这样
NSArray* testArr = @[@{@"key":@"aaa", @"value":@"asdfaf"},
@{@"key":@"baa", @"value":@"bsdfaf"},
@{@"key":@"!!aaa", @"value":@"adsfdfaf"},
@{@"key":@"123aaa", @"value":@"cecdfaf"},
@{@"key":@"@@#21", @"value":@"a42faf"},
@{@"key":@"ace", @"value":@"a123faf"},
@{@"key":@"321!!", @"value":@"123sdfaf"},
];
NSSortDescriptor就像这样
NSLocale *locale = [NSLocale autoupdatingCurrentLocale];
NSSortDescriptor *sortUsingNameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"key" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSWidthInsensitiveSearch | NSForcedOrderingSearch | NSNumericSearch;
NSRange stringRange = NSMakeRange(0, ((NSString *)obj1).length);
return [(NSString*)obj1 compare:(NSString*) obj2 options:comparisonOptions range:stringRange locale:locale];
}];
这是结果。
{
key = "!!aaa";
value = adsfdfaf;
},
{
key = "@@#21";
value = a42faf;
},
{
key = 123aaa;
value = cecdfaf;
},
{
key = "321!!";
value = 123sdfaf;
},
{
key = aaa;
value = asdfaf;
},
{
key = ace;
value = a123faf;
},
{
key = baa;
value = bsdfaf;
}
但我想按照这样排序
{
key = aaa;
value = asdfaf;
},
{
key = ace;
value = a123faf;
},
{
key = baa;
value = bsdfaf;
},
{
key = 123aaa;
value = cecdfaf;
},
{
key = "321!!";
value = 123sdfaf;
},
{
key = "!!aaa";
value = adsfdfaf;
},
{
key = "@@#21";
value = a42faf;
}
是字母,数字和特殊字符序列。 我怎么能这样做
答案 0 :(得分:1)
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:@selector(localizedCompare:)];
NSArray* sortedArray = [inFileTypes sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
答案 1 :(得分:0)
我担心你必须创建自己的比较器。请查看此答案Easy way to put blank strings at end of sort using NSSortDescriptor?