Sort NSMutableArray
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 arrayWithObje开发者_如何学编程ct: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.
There are three solutions:
Put NSNumber instances into the dictionaries in place of the strings (e.g.,
@"100"
) you currently have. NSNumber objects should compare themselves numerically.Send the array a
sortUsingComparator:
orsortUsingFunction:context:
message instead ofsortUsingDescriptors:
, passing a block or function that retrieves the strings and compares them numerically (by sending themcompare:options:
messages with theNSNumericSearch
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.
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.
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:)];
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?
精彩评论