NSDictionary分为两个数组(对象和键),然后由对象数组(或类似的解决方案)进行排序 [英] NSDictionary split into two arrays (objects and keys) and then sorted both by the objects array (or a similar solution)

查看:93
本文介绍了NSDictionary分为两个数组(对象和键),然后由对象数组(或类似的解决方案)进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSDictionary。它有键和对象。

I have an NSDictionary. It has keys and objects.

为了简单起见,键是问题编号,对象是计算答案分数。

For the purposes of simplicity the keys are Question numbers and the objects are calculated Answer scores.

现在,我之前是如何做到的,我将答案分数设置为键,将问题编号设置为对象。通过这种方式,我可以从字典中获取allKeys的数组,对其进行排序,然后执行类似的操作:

Now how I did it before was that I set the answer score as the keys and the question numbers as the objects. This way I could get an array of allKeys from the dictionary, sort it and then do something similar to:

for(NSString *string in tempArray){
  NSLog(@"%@",[dictionary objectForKey:string]);
}

我现在遇到的(我个愚蠢的)问题是那个(显然...... duuhhh)键需要唯一,因此当计算出的答案分数相同时,只输出一个答案!

The (stupid - on my part) problem that I have now encountered however is that (obviously... duuhhh) the keys need to unique, and therefore when the calculated answer scores are the same, only one answer gets output!

我需要一个解决方案对此。在PHP中,您可以 multisort 数组。我想知道在objective-c中是否有类似的解决方案,或者确实有人有更好的答案?

I need a solution to this. In PHP you can multisort arrays. I was wondering if there was some similar solution in objective-c or indeed if someone had a better answer?

这里的任何帮助都会非常感激。

Any help here would be much appreciated.

谢谢。

推荐答案

一种解决方案是使用数组存储答案分数仅包含两个键值对的字典。一个关键是问题编号(或者您的问题被标记,即Q1.1),而另一个关键是实际的答案分数。例如:

One solution is to store the answer scores using an array of dictionaries containing only two key-value pairs. One key is the question number (or however your questions are tagged, i.e. “Q1.1”), while the other key is the actual answer score. For example:

static NSString * const QuestionKey = @"questionNumber";
static NSString * const AnswerScoreKey = @"answerScore";

NSMutableArray *allAnswers = [NSMutableArray array];

for (int i = 0; i < 20; i++)
{
    // fill allAnswers array with random data
    NSDictionary *answer = [NSDictionary dictionaryWithObjectsForKeys:
        [NSString stringWithFormat:@"Q%d", i], QuestionKey,
        [NSNumber numberWithInt:rand()], AnswerScoreKey,
         nil];

    [allAnswers addObject:answer];
}

// sort the allAnswers array based on score, highest first
NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:AnswerScoreKey ascending:NO];

[allAnswers sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];

for (NSDictionary *answer in allAnswers)
{
    NSLog(@"Question: %@, AnswerScore: %@", [answer objectForKey:QuestionKey], [answer objectForKey:AnswerScoreKey];
}



免责声明:



未经测试和未编译的代码。仅限理论。

Disclaimer:

Untested and uncompiled code. Theory only.

这篇关于NSDictionary分为两个数组(对象和键),然后由对象数组(或类似的解决方案)进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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