如何对 NSArray 进行自然排序? [英] How to do a natural sort on an NSArray?

查看:92
本文介绍了如何对 NSArray 进行自然排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我需要按标题"键对它们进行排序.它目前正在工作,尽管它使用的是 ASCII 排序而不是自然排序.标题是文件名,所以它们看起来像这样:

I have 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:

文件1
文件2
文件3
...
文件10
文件11
文件12

file1
file2
file3
...
file10
file11
file12

正如你所料,我得到了:

I'm getting, as you would expect:

文件1
文件10
文件11
文件12
文件2
文件3
...

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.

推荐答案

NSStrings 可以是 比较 使用NSNumericSearch 比较选项.

NSStrings 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆