【问题标题】:Add to dictionary from array of keys从键数组添加到字典
【发布时间】:2012-06-03 17:53:00
【问题描述】:

在过去的几天里,我一直在努力解决以下问题

我需要在字典的字典深处设置一个键和一个值。我知道要设置键的字典的键,但我不知道如何到达那里。 密钥存储在一个数组中。

说,我有一个包含以下键的字典,每个键的值是另一个字典。

- myDict
    - A
      - A
        - A
        - B
      - B
        - A
        - B
    - B
      - A
        - A
        - B
      - B
        - A
        - B

我还有以下数组:

[A, A, B]

这意味着,我想为字典中 A->A->B 的键设置一个值。 这等于以下内容:

[[[[myDict objectForKey:@"A"] objectForKey:@"A"] objectForKey@"B"] setValue:myValue forKey:myKey]

有谁知道我可以实现这一目标的方法吗? 我想我应该保留对字典的引用,遍历数组中的对象并转到字典中的“下一级”并保留对此的引用,当到达数组中的最后一个对象时,设置键的值。我的问题是,我不知道如何解决这个问题。为了保持对字典的引用,当我进入下一个级别时,我需要初始化一个新字典,对吗?这导致我创建一个只包含当前级别对象的新字典,因此我最终不会为原始字典中的键设置值。

任何代码示例或伪代码将不胜感激。

【问题讨论】:

  • 你试过递归吗? (我不希望它嵌套太深,但即使是这样,也可以将递归转换为带堆栈的循环)
  • 我看不到什么时候会初始化新字典...?

标签: iphone objective-c arrays dictionary


【解决方案1】:

在我看来,您只需使用[yourArray componentsJoinedByString:@"."] 来获取密钥路径,然后使用valueForKeyPath: 来获取适当的值。

【讨论】:

  • 这正是我一直在寻找的!轻松优雅。非常感谢。
【解决方案2】:

你会做这样的事情,不是说这是“确切”的答案,而是应该让你弄清楚你的确切需求。

for(NSString* key in [myDict allKeys]) {

    NSString *yourValue = ....
    NSDictionary *dict = [[myDict objectForKey:key] objectForKey:key];// Will get you to A->A

    for(NSString *levelKey in [dict allKeys]) {

    //Setting Value for A->A->(A) & A->A->(B)

          [dict setValue:yourValue forKey:levelKey];      
    }

}

【讨论】:

    【解决方案3】:

    这个答案应该被忽略。相反,请使用@Chuck 发布的方法。

    我最终编写了以下两种方法来解决问题。这是受到@nhahtdh 的启发。 这些方法非常适合一个类别,但我以前从未写过一个类别。有一天,我可能会将这些归为一类。如果有人想这样做,请在此处发布结果。

    /**
     *  Sets the value in a dictionary with a keypath. Uses either the first or the last key in the keypath as the key to set the value for.
     *  @param value Value to set.
     *  @param dictionary Dictionary to set the value in.
     *  @param path Path for the key. Last or first object is used as the key for the value.
     *  @param readFromEnd Whether or not to read the path from the end.
     */
     + (void)setValue:(id)value inDictionary:(NSMutableDictionary *)dictionary withKeyPath:(NSArray *)path readFromEnd:(BOOL)readFromEnd
    {
        NSMutableArray *mutablePath = [NSMutableArray arrayWithArray:path];
        NSString *key;
        if (readFromEnd)
        {
            key = [mutablePath lastObject];
            [mutablePath removeLastObject];
        }
        else
        {
            key = [mutablePath objectAtIndex:0];
            [mutablePath removeObjectAtIndex:0];
        }
        [self setValue:value forKey:key inDictionary:dictionary withKeyPath:mutablePath readFromEnd:readFromEnd];
    }
    
    /**
     *  Sets the value in a dictionary with a keypath.
     *  @param value Value to set.
     *  @param key Key for the value.
     *  @param dictionary Dictionary to set the value in.
     *  @param path Path for the key.
     *  @param readFromEnd Whether or not to read the path from the end.
     */
    + (void)setValue:(id)value forKey:(NSString *)key inDictionary:(NSMutableDictionary *)dictionary withKeyPath:(NSArray *)path readFromEnd:(BOOL)readFromEnd
    {
        if (path.count == 0)
            [dictionary setValue:value forKey:key];
        else
        {
            NSMutableArray *mutablePath = [NSMutableArray arrayWithArray:path];
            NSString *currentKey;
            if (readFromEnd)
            {
                currentKey = [mutablePath lastObject];
                [mutablePath removeLastObject];
            }
            else
            {
                currentKey = [mutablePath objectAtIndex:0];
                [mutablePath removeObjectAtIndex:0];
            }
            [self setValue:value forKey:key inDictionary:[dictionary objectForKey:currentKey] withKeyPath:mutablePath readFromEnd:readFromEnd];
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      相关资源
      最近更新 更多