Sort NSMutableArray

2019-09-13 01:54发布

please help me I want to sort NSMutableArray and yes I can do this by

NSSortDescriptor *sortPoint = [[NSSortDescriptor alloc] initWithKey:@"point" ascending:YES];
[hightScore sortUsingDescriptors:[NSArray arrayWithObject:sortPoint]];

but in NSMuatableArray(hightScore), I have 2 NSMutableDictionary like this

[item setObject:@"player_name" forKey:@"name"];
[item setObject:@"100" forKey:@"point"];

and when I sort by keyword "point" that is string it give me like this 100 > 20 > 30 > 50 instead should be 20 > 30 > 50 > 100

have any idea pleassss.

3条回答
贪生不怕死
2楼-- · 2019-09-13 02:05

The best way to do this is to store your numbers as NSNumbers:

[index addObject:[[NSNumber alloc] initWithInt:number]];

Then you can sort your array using the [NSNumber compare:] method:

[index sortUsingSelector:@selector(compare:)];
查看更多
一夜七次
3楼-- · 2019-09-13 02:05
NSMutableArray* tempArray = [NSMutableArray arrayWithArray:anArray];
[tempArray sortUsingSelector:@selector(caseInsensitiveCompare:)];

I use this in some code? Will this work?

Also, just noticed you are setting the array objects as strings which I'm assuming will also be an issue. Try adding them as NSIntegers or ints... does that work at all?

查看更多
迷人小祖宗
4楼-- · 2019-09-13 02:08

There are three solutions:

  1. Put NSNumber instances into the dictionaries in place of the strings (e.g., @"100") you currently have. NSNumber objects should compare themselves numerically.
  2. Send the array a sortUsingComparator: or sortUsingFunction:context: message instead of sortUsingDescriptors:, passing a block or function that retrieves the strings and compares them numerically (by sending them compare:options: messages with the NSNumericSearch option).

    Note that the block or function will be passed the whole dictionaries, not the strings, since it has no way to know which strings to extract, so you'll have to get the strings out of the dictionaries yourself in order to compare them.

  3. Replace the dictionaries with model objects that have properties in place of the dictionary keys. If you declare the property with a numeric type (e.g., NSUInteger), then when the array uses KVC to access the property, it will get NSNumber objects, which, as noted under #1 above, should compare themselves numerically.

I would go with #3.

查看更多
登录 后发表回答