NSDictionary键按值以数字排序

Mat*_*att 18 sorting cocoa-touch objective-c nsdictionary

我将名称作为键存储,并将值作为值存储到NSDictionary保存中NSUserDefaults.然后我想要取回按分数排序的键,但我似乎无法用数字排序它们,只能用字符串.例如,分数列表100,50,300,200,500给出了100,200,300,50,500.

可以这样做还是我需要以不同的方式解决这个问题?

NSString *defaultNames[] = {@"Matt", @"Terry",@"Jessica",@"Sean",nil};
NSNumber *defaultScores[] = {@"600", @"500",@"100",@"50", nil};

NSDictionary *newScoreDict =  [NSDictionary dictionaryWithObjects:(id *)defaultScores forKeys:(id *)defaultNames count:7];

NSArray *currScores = [scoreDict keysSortedByValueUsingSelector:@selector(compare:)];
Run Code Online (Sandbox Code Playgroud)

leu*_*ima 7

如何使用keysSortedByValueUsingSelector(NSDictionary)

根据XCode中的文档,似乎是您所需要的

  • @hmak:不.你一定在想`keysSortedByValueUsingComparator:`帖子提到`keysSortedByValueUsingSelector:`,自10.0以来一直可用 (2认同)

小智 5

NSString *defaultNames[] = {@"Matt", @"Terry",@"Jessica",@"Sean",nil};
NSNumber *defaultScores[] = {@"600", @"500",@"100",@"50", nil};
NSDictionary *newScoreDict =  [NSDictionary dictionaryWithObjects:(id *)defaultScores forKeys:(id *)defaultNames count:7];
NSArray *currScores = [scoreDict keysSortedByValueUsingSelector:@selector(localizedStandardCompare:)];
Run Code Online (Sandbox Code Playgroud)


NSR*_*der 2

-compare:是字符串比较。通过不同的方法进行比较,例如:

@implementation NSString (numericComparison)

- (NSComparisonResult) compareNumerically:(NSString *) other
{
float myValue = [self floatValue];
float otherValue = [other floatValue];
if (myValue == otherValue) return NSOrderedSame;
return (myValue < otherValue ? NSOrderedAscending : NSOrderedDescending);
}

@end
Run Code Online (Sandbox Code Playgroud)

在您的具体情况下,您可以使用 -intValue 代替。