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:)];
I store names as keys and scores as values into an NSDictionary
for saving in NSUserDefaults
. I then want to get back the keys sorted by score, but I can't seem to sort them numerically, only by string. The list of scores 100, 50, 300, 200, 500, for example, gives me 100, 200, 300, 50, 500.
Can this be done or do I need to go about this differently?
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:)];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如何使用keysSortedByValueUsingSelector (NSDictionary)
似乎是您所需要的,根据XCode中的文档
how about using keysSortedByValueUsingSelector (NSDictionary)
Seems to be what you need as per the documentation in XCode
我仍然对前一行感到困惑?
我是否只使用
数字数组是否可以,还是有更简单的方法?
非常感谢...
I am still confused with the previous line ?
Do I just use
Is the array of numbers OK, or is there an easier way ?
Thank You Very Much...
-compare:是字符串比较。传递不同的方法进行比较,例如:
在您的具体情况下,您可以使用 -intValue 代替。
-compare: is a string compare. Pass a different method for the comparison, e.g:
In your specific case, you could use -intValue instead.
不确定这是否有帮助,但您也可以将 NSArray 保存在 plist 中;与 NSDictionary(它以基本上随机的顺序返回键)不同,您可以在放入键时将它们取回。
Not sure it would help, but you can also save an NSArray in a plist; unlike an NSDictionary (which returns keys in essentially random order), you get them back as you put them in.
我认为这个问题最简单的方法是使用比较器..
试试这个..
我注意到我无法使用 NSNumber 对象达到值,因此如果您想达到对象值,那么我可以通过将 NSNumber 分数更改为 NSString 并在订购时将它们转换为数字来解决。您可以像下面一样使用..
希望它有帮助..
I think simplest way of this question is using comparator..
try this..
I noticed that i couldnt reach value with using NSNumber object so if you want to reach object value than i solved with changing your NSNumber scores to NSString and convert them to numbers while ordering. You can use like below..
Hope it helps..