Sort NSMutableDictionary keys by object?

强颜欢笑 提交于 2019-12-25 02:20:19

问题


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}.


回答1:


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];
}

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.




回答2:


These constants are used to indicate how items in a request are ordered.

enum {
   NSOrderedAscending = -1,
   NSOrderedSame,
   NSOrderedDescending
};
typedef NSInteger NSComparisonResult;

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 :)




回答3:


NSArray *sortedArray = [searchWords sortedArrayUsingSelector:@selector(compare:) ];

or you might well as used, here is the implementation of your intCompare selector

- (NSComparisonResult) intCompare:(NSString *) other
{
    int myValue = [self intValue];
    int otherValue = [other intValue];
    if (myValue == otherValue) return NSOrderedSame;
    return (myValue < otherValue ? NSOrderedAscending : NSOrderedDescending);

}



来源:https://stackoverflow.com/questions/6956277/sort-nsmutabledictionary-keys-by-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!