【问题标题】:How to insert a new key with value in dictionary如何在字典中插入具有值的新键
【发布时间】:2011-05-16 05:06:10
【问题描述】:

我想在现有字典中插入一个具有相应值的键...

我可以为字典中的现有键设置值,但我无法添加新键值...

任何帮助将不胜感激。

【问题讨论】:

    标签: iphone key nsmutabledictionary


    【解决方案1】:

    使用 NSMutableDictionary

    NSMutableDictionary *yourMutableDictionary = [NSMutableDictionary alloc] init];
    [yourMutableDictionary setObject:@"Value" forKey:@"your key"];
    

    Swift 更新:

    以下是上述代码的确切 swift 副本

    var yourMutableDictionary = NSMutableDictionary()
    yourMutableDictionary.setObject("Value", forKey: "Key")
    

    但我建议你使用 Swift Dictionary 方式。

    var yourMutableDictionary = [String: AnyObject]() //Open close bracket represents initialization
    
    //The reason for AnyObject is a dictionary's value can be String or
    //Array or Dictionary so it is generically written as AnyObject
    
    yourMutableDictionary["Key"] = "Value"
    

    【讨论】:

    • 如何知道给定键在字典中是否存在
    • [yourMutableDictionary allKeys];这将返回该字典中所有键的数组,并将其与您给定的键进行比较并知道它
    • 顺便说一下,如果你要转换回 NSDictionary,你可以像 yourNSDictionary = yourMutableDictionary as NSDictionary 一样转换它。
    • 以及如何添加任何对象类作为值和int作为键?
    【解决方案2】:
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    

    通过使用这种方法,我们可以将新值添加到 NSMutableDictionary

    [dict setObject:@"Value" forKey:@"Key"];
    

    要知道字典中是否存在键

    [[dict allKeys] containsObject:@"key"];
    

    【讨论】:

    • cv::Mat 作为值,int 作为键如何将其添加到 NSMutableDictionary?
    【解决方案3】:

    您好,我从 json 中获取字典格式的内容,然后我将内容添加到其他字典中

      //here contract is my json dictionary 
      NSArray *projectDBList =[contract allKeys];//listing all the keys in dict 
    
      NSMutableDictionary *projectsList=[[NSMutableDictionary alloc]init];
    
      [projectDBList enumerateObjectsUsingBlock:^(NSString * obj, NSUInteger idx, BOOL *stop) {
    
      [projectsList setObject:[contract objectForKey:obj] forKey:obj];
    
      }];
    

    【讨论】:

      【解决方案4】:

      NSDictionnary 是不可变的。请改用 NSMuteableDictory。

      adding 对象:setObject:forKey:

      测试密钥是否存在:

      [[aDict allKeys] containsObject:@"key"];
      

      【讨论】:

      • 对于nsmutable字典如何插入新的键值
      猜你喜欢
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多