如何做一个自然排序在一个NSArray? [英] How to do a natural sort on an NSArray?
问题描述
我有一个对象数组,我需要他们按他们的标题键排序。它目前工作,虽然它使用ASCII排序而不是自然排序。标题是文件名,因此它们如下所示:
I've got an array of objects, and I need them sorted by their "title" key. It's currently working, though it's using an ASCII sort instead of a natural sort. The titles are filenames, so they look like this:
file1
file2
file3
...
file10
file11
file12
file1
file2
file3
...
file10
file11
file12
expect:
file1
file10
file11
file12
file2
file3
...
file1
file10
file11
file12
file2
file3
...
有人知道是否有一种内置于NSArray排序功能的方法得到这个自然排序而不是字母排序?我找到一些通用的算法,但我希望有一些内置的...
Does anyone know if there is a way built-in to the NSArray sorting functionality to get this natural sorting as opposed to the alphabetical sort? I found some generic algorithms, but I was hoping for something built-in...
推荐答案
NSString
可以比较,使用 NSNumericSearch 比较选项。
NSString
s can be compared using the NSNumericSearch compare option.
一个版本:
NSInteger sort(Obj* a, Obj* b, void*) {
return [[a title] compare:[b title] options:NSNumericSearch];
}
result = [array sortedArrayUsingFunction:&sort context:nil];
或更加通用:
NSInteger sort(id a, id b, void* p) {
return [[a valueForKey:(NSString*)p]
compare:[b valueForKey:(NSString*)p]
options:NSNumericSearch];
}
result = [array sortedArrayUsingFunction:&sort context:@"title"]
或使用块:
result = [array sortedArrayUsingComparator:^(Obj* a, Obj* b) {
return [[a title] compare:[b title] options:NSNumericSearch];
}];
这篇关于如何做一个自然排序在一个NSArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!