How to insert a new key with value in dictionary
Asked Answered
L

4

30

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 a new key value...

Any help would be appreciated.

Lyly answered 26/11, 2010 at 13:59 Comment(0)
L
52

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"
Lornalorne answered 26/11, 2010 at 14:6 Comment(4)
how to know whether the given key is existed or not in dictionaryLyly
[yourMutableDictionary allKeys]; This will return an array of all keys in that dictionary and compare that with your given key and know itLornalorne
By the way, if you have to convert back to a NSDictionary you can by casting it like yourNSDictionary = yourMutableDictionary as NSDictionary.Accessary
and how to add any object class as value and int as key?Sealskin
R
2

NSDictionnary is immutable. Use NSMuteableDictiory instead.

adding Objects: setObject:forKey:

Testing if key is present:

[[aDict allKeys] containsObject:@"key"];
Rouge answered 26/11, 2010 at 14:3 Comment(1)
for nsmutable dictionary how to insert new key valueLyly
D
2
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"];
Devitt answered 15/11, 2013 at 9:49 Comment(1)
cv::Mat as value and int as key how to add it to NSMutableDictionary?Sealskin
S
2

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];

  }];
Sealer answered 2/7, 2014 at 9:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.