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
372 views
in Technique[技术] by (71.8m points)

ios - Sorting NSArray which many contain number

I have an NSArray which is populated with objects from an NSMutableArray. Most of these object have integer values like "1", "2", "3", "4", "5", sometimes there is a name like "home", "far left", or "far right". I am trying to sort this array in Objective C. using sortedArrayUsingSelector:@selector(compare:) works fine when I have less then 10 items in the array. but when it there are more I start getting "1", "10", "11", "12", "2", "3" type of stuff. Any help would be most appreciated. The code should not return anything. It just needs to sort and move on.

Original Code:

presetNamesSort = [[[NSMutableArray alloc]init]retain];

presetNamesSort = [presetNames sortedArrayUsingSelector:@selector(compare:)];
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can use NSArray's -sortedArrayUsingComparator: method to get a sorted array using a custom block. I find this more convenient than -sortedArrayUsingSelector:, because you can declare the comparator inline, like so:

NSArray *unsortedArray = [NSArray arrayWithObjects:@"Hello", @"4", @"Hi", @"5", @"2", @"10", @"1", nil];
NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(NSString *str1, NSString *str2) {
    return [str1 compare:str2 options:NSNumericSearch];
}];

This will return an array that looks like so:

(
    1,
    2,
    4,
    5,
    10,
    Hello,
    Hi
)

In general, it's pretty nice to use blocks because they eliminate the need to create random selectors that run amuk in your code.


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

...