2011-08-05 38 views
0

散景。這裏是協議: 有一個NSMutualDictionary與單詞作爲鍵(說名字)。值對象是一個NSNumber(如評級)按對象排序NSMutableDictionary鍵?

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。

回答

1

既然你把字典中的對象NSNumber實例您應該稍微更改方法簽名。但全面實施是很容易的:

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

其實我看不出有任何理由,爲什麼你需要做自己的intCompare:方法,當你可以用compare:NSNumber已經走了。

+0

是的,tjats正確。我的印象是隻有NSString比較:實施。但是因爲NSNumber也應該這樣做。現在我該如何設置A的結尾或下降方向? – esbenr

+0

但還有一個問題。使用選擇器(比較:)按對象對字典進行排序,但先將最低值排序。我如何改變他的排序方向? – esbenr

+1

@esbenr - 對此沒有直接的支持。但是你可以使用' - [NSDictionary keysSortedByValueUsingComparator:]'來做你自己的反轉比較。 – PeyloW

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

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

這是從蘋果的dev documentataion取得的數據類型...現在你所要做的就是檢查哪一個更大。所有這些都是爲你完成的。只需傳入@selector(比較:)並且應該這樣做。因爲你的值是NSNumbers而NSNumber實現了compare:功能。這是你想要的東西:)

+0

1pt指向與PeyloW相同:-) – esbenr

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

,或者您可能還有用,這裏是你的intCompare選擇的實施

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

}

+0

您應該接受答案以及它可能會對其他人有所幫助:) –

+0

我只能接受一個答案(我沒有在這裏制定規則)和PeyloW的答案解決了我的問題。 – esbenr