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)
如何使用keysSortedByValueUsingSelector(NSDictionary)
根据XCode中的文档,似乎是您所需要的
小智 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)
-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 代替。
| 归档时间: |
|
| 查看次数: |
22450 次 |
| 最近记录: |