NSDictionary - 获取唯一记录,选择哪些键必须是唯一的

时间:2017-10-24 10:12:45

标签: ios objective-c nsdictionary

我有一组带有N键的词典。我想创建一个唯一的dicts数组,它只包含一些键。

实施例。我的命令:

{
    "m_anno" = 2017;
    "m_c_ultimo" = "4.130";
    "m_cod" = 4522;
    "m_cod_art" = "*B";
    "m_des" = "SCRITTA BIANCA NISSAN";
    "m_ditta" = SIS;
    "m_prz" = "0.000";
    "m_qta" = "1.000";
    "m_sconto" = {
    };
},
{
    "m_anno" = 2017;
    "m_c_ultimo" = "25.020";
    "m_cod" = 4522;
    "m_cod_art" = "000/01200";
    "m_des" = "CABLAGGIO X TIMONE";
    "m_ditta" = SIS;
    "m_prz" = "0.000";
    "m_qta" = "1.000";
    "m_sconto" = {
    };
},
{
    "m_anno" = 2017;
    "m_c_ultimo" = "1.000";
    "m_cod" = 4523;
    "m_cod_art" = 000000;
    "m_des" = "BLISTER O-RING 3106";
    "m_ditta" = SIS;
    "m_prz" = "0.000";
    "m_qta" = "1.000";
    "m_sconto" = {
    };
},

我想获得m_anno和m_cod键的唯一值。预期结果:

{
  {
     "m_anno" = 2017
     "m_cod" = 4522
  }
  {
      "m_anno" = 2017
      "m_cod" = 4523
  }
}

哪种方法最简单?

1 个答案:

答案 0 :(得分:0)

基本上你必须迭代数组(quelle surprise!)并把它放在一个集合中,如果这对尚未存在的话。第二项任务可以通过使用NSSetNSOrderedSet的实例来完成,具体取决于必须保留订单的要求:

NSArray *values = …; // You start with this
NSMutableOrderedSet *uniquePairs = [NSMutableOrderedSet new];
for( NSDictionary *value in values )
{
   NSDictionary *pair = @{ @"m_anno":[value objectForKey:@"m_anno"], @"m_cod":[value objectForKey:@"m_cod"] }; // Create smaller version
   [uniquePairs addObject:pair];
}

可能有更优雅的方式。 (取决于观点)

创建字典的附加内容,将数组缩减为所需的键:

NSDictionary( UnifyAnnoAndCodeAddition )
- (NSDictionary*)annoAndCod
{
  return @{ @"m_anno":[self objectForkey:@"m_anno"], @"m_cod":[self objectForKey:@"m_code"]};
}

然后使用键值编码创建缩减词典的数组并制作一组:

NSArray *values = …; // You start with this
NSArray *pairs = [values valueForKey:@"annoAndCod"]; 
NSOrderedSet = [NSOrderedSet orderedSetWithArray:pairs];

嗯,至少它更短。