-2

I am trying to add NSMutableArray's to a NSMutableDictionary

My code looks something like this:

[myDictionary setObject:[NSMutableArray array] ForKey: myKey];
[[myDictionary objectForKey:myKey] addObject: myString];

So what I am trying to do: I have an empty dictionary, and I want to have multiple arrays within that dictionary. Each array has it's own key. In each array I want to add a NSString, so that each array will fill up with several NSString Objects.

But, when I try to check the contents of myDictionary by using:

for(id key in myDictionary)
{
    NSLog(@"key=%@ value=%@", key, [myDictionary objectForKey:key]);
}

I will only get one entry for each key. What am I doing wrong?

Thanks in advance, and sorry for the noobness

Pieter
  • 3
  • 2
  • 1
    Show your code where you add more than one value to each array. – rmaddy Dec 02 '14 at 23:12
  • First off, don't "chain" calls like that. Create your array, assign the address to a temporary pointer, then insert that pointer into the dictionary. And to add objects to the array, get the address of it into a temporary pointer, then use that to add entries. Use meaningful names for the temporary pointers. This will be much less confusing (for me, if not for you). – Hot Licks Dec 02 '14 at 23:21

1 Answers1

0

Your code appears to be correct, it should simply print out a list of the strings in each array inside the NSDictionary. Are you adding more than one string object to the array? If there's only one value then of course it will only print one value :)

If you want to access each value in the array(s) individually, try this:

for(id key in myDictionary)
{
    NSArray *array = [myDictionary objectForKey:key];
    for (NSString *value in array) {
        NSLog(@"value: %@", value);
    }
}
JoGoFo
  • 1,928
  • 14
  • 31
  • Ah, there seems to be that I misunderstood a part of my code, I thought that: "[[myDictionary objectForKey:myKey] addObject: myString];" this, would add a NSString to a certain array at that key. Which, reading from your kind answer and other comments, it clearly doesn't – Pieter Dec 02 '14 at 23:33
  • That's exactly what it is doing. Consider an NSDictionary to be a type of array which is accessed with a string instead of a number. The layout is something like this: NSDictionary { "somekey" : Array (item1, item2, item3), "someotherkey" : Array (item4, item5, item6) } So with a single "for in" statement, you are iterating over the Objects in the NSDictionary only. Each of those objects is an NSArray. The nested "for in" statement then iterates over the Objects in each of the NSArrays. – JoGoFo Dec 03 '14 at 03:12