Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

objective c - How to do a natural sort on an NSArray?

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:

file1
file2
file3
...
file10
file11
file12

I'm getting, as you would expect:

file1
file10
file11
file12
file2
file3
...

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.

question from:https://stackoverflow.com/questions/2846301/how-to-do-a-natural-sort-on-an-nsarray

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

NSStrings can be compared using the NSNumericSearch compare option.

One version:

NSInteger sort(Obj* a, Obj* b, void*) {
    return [[a title] compare:[b title] options:NSNumericSearch];
}

result = [array sortedArrayUsingFunction:&sort context:nil];

Or a bit more generic:

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"]

Or using blocks:

result = [array sortedArrayUsingComparator:^(Obj* a, Obj* b) { 
    return [[a title] compare:[b title] options:NSNumericSearch]; 
}];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...