Allreadyhome
Allreadyhome

Reputation: 1262

Add to NSMutableDictionary without replacing similar keys

I am dynamically populating a NSMutableDictionary with keys that are identical. However doing so replaces the original keys value. What I require is it to be appended and not replacing the existing key. For example, I need a structure like

    {
      @"Key" : @"Value1",
      @"Key" : @"Value2",
      @"Key" : @"Value3"
    }

I know I could add each NSDictionary that is created to a NSMutableArray but my issue comes because I need the input value to be a NSDictionary.

Currently I have the following which replaces the original value

  NSMutableDictionary *ripDictionary = [[NSMutableDictionary alloc] init];

    for(NSString *ripId in recievedRips){

        //SOME OTHER CODE

        ripDictionary[@"rip"] = keysAndAttributes;

        [data addObject:ripDictionary];
    }

Upvotes: 0

Views: 197

Answers (2)

Frankie
Frankie

Reputation: 11918

From the NSDictionary Reference

A key-value pair within a dictionary is called an entry. Each entry consists of one object that represents the key and a second object that is that key’s value. Within a dictionary, the keys are unique. That is, no two keys in a single dictionary are equal (as determined by isEqual:).

Perhaps you could modify your code to accept a dictionary like:

{
      @"Key" : [
               @"Value1",
               @"Value2",
               @"Value3"
           ]
}

Upvotes: 3

Cooper Buckingham
Cooper Buckingham

Reputation: 2524

You can only have a single unique key per dictionary, so if you want multiple values associated with it then you would add those values to an array associated with the key.

if([aDictionary objectForKey:@"key"] != nil){
  aDictionary[@"key"] = @[aDictionary[@"key"], bDictionary[@"key"]];
}else{
  aDictionary[@"key"] = bDictionary[@"key"];
  //OR make all aDictionary values array by default with a single value
  //but you get the point
}

Upvotes: 1

Related Questions