Sort NSMutableArray

2019-09-13 02:18发布

问题:

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.

回答1:

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.



回答2:

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:

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?