簡體   English   中英

根據其值對可變字典進行排序

[英]Sort mutable dictionary based on values of it

我有一個無序的NSMutableDictioanry,並且此dictioanry如以下示例所示創建

{
    1 = 27;
    2 = 5;
    3 = 13964;
    4 = 2422;
    5 = 45;
    6 = 7;
    7 = 27;
    8 = 39;
}

我想根據值對這本字典進行排序。 可以根據以下文章完成此操作,並且可以很好地正常工作獲取按其各自值排序的NSDictionary鍵 ,並將返回一個數組,其中包含根據值排序的鍵

(
    2,
    6,
    7,
    1,
    8,
    5,
    4,
    3
)

所以我的問題是無論如何我都可以直接獲得排序字典而不是數組

我不是並行對象的忠實擁護者,但您可能希望擁有一組排序的鍵和字典。

早期,已設置字典(可能在-viewWillAppear: )。

self.sortedKeys = [self.dictionary keysSortedByValueUsingSelector:@selector(compare:)];

然后在-tableView:cellForRowAtIndexPath:使用

NSNumber *key = self.sortedKeys[indexPath.row];
NSNumber *value = self.dictionary[key];

作為非並行對象解決方案,您可以使用數組將鍵值對存儲為兩個項的數組。 keyValuePair[0]是鍵, keyValuePair[1]是值。

- (NSArray *)sortedDataFromDictionary:(NSDictionary *)dictionary {
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:dictionary.count];

    for (NSNumber *key in [dictionary keysSortedByValueUsingSelector:@selector(compare:)]) {
        NSArray *keyValuePair = @[key, dictionary[key]];
        [result addObject:keyValuePair];
    }

    return [result copy];
}

早期,已設置字典(可能在-viewWillAppear: )。

self.sortedData = [self sortedDataFromDictionary:dictionary];

然后在-tableView:cellForRowAtIndexPath:使用

NSNumber *key = self.sortedData[indexPath.row][0];
NSNumber *value = self.sortedData[indexPath.row][1];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM