按对象对NSMutableDictionary键进行排序? [英] Sort NSMutableDictionary keys by object?

查看:66
本文介绍了按对象对NSMutableDictionary键进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧.这是交易:拥有一个以单词为键的NSMutualDictionary(例如名称).值对象是NSNumber(例如评分)

Okeh. Here is the deal: Have have a NSMutualDictionary with words as keys (say names). The value objects is a NSNumber (like rating)

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:[NSNumber intValue:1] forKey:@"Melvin"];
[dictionary setObject:[NSNumber intValue:2] forKey:@"John"];
[dictionary setObject:[NSNumber intValue:3] forKey:@"Esben"];

我想首先对评分最高的邮件进行排序.

I want to sort them with the highest ratings first.

我知道我要这样做:

[searchWords keysSortedByValueUsingSelector:@selector(intCompare:)];

但不确定如何实现intCompare.(比较方法)

But not sure how to implement intCompare. (the compare method)

有人能指出我正确的方向吗?

Can anybody point me in the right direction?

- (NSComparisonResult) intCompare:(NSString *) other
{
//What to do here?
}

我想使用{Esben,John,Melvin}获得一个NSArray.

I want to get an NSArray with {Esben, John, Melvin}.

推荐答案

由于您放入字典中的对象是 NSNumber 实例,因此应稍微更改方法签名.但是完整的实现非常容易:

Since the objects you put into the dictionary are NSNumber instances you should change the method signature a bit. But the full implementation is really easy:

-(NSComparisonResult)intCompare:(NSNumber*)otherNumber {
    return [self compare:otherNumber];
}

实际上,我看不出为什么需要使用自己的 intCompare:方法,当您可以使用 NSNumber 已经拥有.

In fact I see no reason as to why you need to do your own intCompare: method, when you could go with the compare: that NSNumber already has.

这篇关于按对象对NSMutableDictionary键进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆