Sort NSMutableArray

please help me I want to sort NSMutableArray and yes I can do it with

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 the keyword "dot", this is a string, I like it 100> 20> 30> 50 instead it should be 20> 30> 50> 100

have any idea.

0
source share
3 answers

There are three solutions:

  • Put the NSNumber instances in the dictionaries instead of the strings (like @"100" ) that you have. NSNumber objects must compare themselves numerically.
  • Send an array a sortUsingComparator: or sortUsingFunction:context: message instead of sortUsingDescriptors: passing a block or function that extracts the strings and compares them numerically (by sending them compare:options: with the NSNumericSearch parameter).

    Note that a block or function will be passed in whole dictionaries, not strings, because it does not have the ability to know which strings to extract, so you have to output the strings from the dictionaries yourself to compare them.

  • Replace dictionaries with model objects that have properties instead of dictionary keys. If you declare a property with a numeric type (for example, NSUInteger ), then when the array uses KVC to access the property, it will receive NSNumber objects, which, as indicated in # 1 above, must compare themselves numerically.

I would go with number 3.

+1
source

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

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

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

 [index sortUsingSelector:@selector(compare:)]; 
+1
source
 NSMutableArray* tempArray = [NSMutableArray arrayWithArray:anArray]; [tempArray sortUsingSelector:@selector(caseInsensitiveCompare:)]; 

Am I using this in some code? Will this work?

Also, you just noticed that you are setting array objects as strings, which I assume will also be a problem. Try adding them as NSIntegers or ints ... does this even work?

0
source

Source: https://habr.com/ru/post/886548/


All Articles