按对象对 NSMutableDictionary 键进行排序?
好吧。这是交易: 有一个 NSMutualDictionary,以单词为键(比如名字)。值对象是一个 NSNumber (如评级),
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"];
我想首先对它们进行最高评级的排序。
我知道我会这样做:
[searchWords keysSortedByValueUsingSelector:@selector(intCompare:)];
但不确定如何实现 intCompare。 (比较方法)
有人能指出我正确的方向吗?
- (NSComparisonResult) intCompare:(NSString *) other
{
//What to do here?
}
我想用 {Esben, John, Melvin} 获得一个 NSArray。
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.
I know I'm going to do it like this:
[searchWords keysSortedByValueUsingSelector:@selector(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?
}
I want to get an NSArray with {Esben, John, Melvin}.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于放入字典中的对象是
NSNumber
实例,因此您应该稍微更改方法签名。但完整的实现非常简单:事实上,当您可以使用
compare:
时,我认为没有理由需要执行自己的intCompare:
方法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:In fact I see no reason as to why you need to do your own
intCompare:
method, when you could go with thecompare:
thatNSNumber
already has.这是取自苹果关于数据类型的开发文档......现在您所要做的就是检查哪一个更大。不过,这一切都是为你做的。只需传入 @selector(compare:) 即可。由于您的值是 NSNumbers 并且 NSNumber 实现了 Compare: 函数。这就是你想要的:)
That is taken from Apple's dev documentataion on Data types... now all you have to do is check which one is bigger. All of this is done for you though. Simply pass in @selector(compare:) and that should do it. As your values are NSNumbers and NSNumber implements the compare: function. Which is what you want :)
或者您可能会使用,这是您的 intCompare 选择器的实现
}
or you might well as used, here is the implementation of your intCompare selector
}