How to insert a new key with value in dictionary

前端 未结 4 904
情话喂你
情话喂你 2020-12-18 18:17

I want to insert a key with a corresponding value in an existing dictionary...

I am able to set values for existing keys in the dictionary, but I am not able to add

相关标签:
4条回答
  • 2020-12-18 18:28

    Use NSMutableDictionary

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

    Update for Swift:

    The following is the exact swift replica for the code mentioned above

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

    But i would suggest you to go with Swift Dictionary way.

    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"
    
    0 讨论(0)
  • 2020-12-18 18:41

    Hi I am getting the content from json in the format of dictionary and from that i am adding the content into some other dictionary

      //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];
    
      }];
    
    0 讨论(0)
  • 2020-12-18 18:45
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    

    By using this method we can add the new value to NSMutableDictionary

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

    To know wheather the key exist in dictionary

    [[dict allKeys] containsObject:@"key"];
    
    0 讨论(0)
  • 2020-12-18 18:45

    NSDictionnary is immutable. Use NSMuteableDictiory instead.

    adding Objects: setObject:forKey:

    Testing if key is present:

    [[aDict allKeys] containsObject:@"key"];
    
    0 讨论(0)
提交回复
热议问题