2

I have the following key values in my dictionary, I am trying to loop through every row and log every item, is this possible using an NSDictionary?

Notice that my keys are not unique

Key     Value
A         1
B         2
B         3
B         4
C         5
C         6
C         7
D         8
aryaxt
  • 76,198
  • 92
  • 293
  • 442

5 Answers5

5

In a dictionnary, keys are unique.

You must have one value per key.

Victor Carmouze
  • 947
  • 6
  • 10
4

It might be the bad way to do it, but if your dictionary is not too big you can try that:

Key     Value
1     Array with "A" and "1"
2     Array with "B" and "2"
3     Array with "B" and "3"
//and so on

Then you can easily loop through it and log what you need(in this case [theArray objectAtIndex:1]).

Hope it helps

Novarg
  • 7,390
  • 3
  • 38
  • 74
1

I notice your second values are contiguous numbers--therefore, are you sure you don't mean to use an NSArray (an ordered list) containing "A", "B", "B", "B", "C", "C", "C", "D"? Then to loop through:

NSArray* array = [NSArray arrayWithObjects:@"A", @"B", @"B", @"B", @"C", @"C", @"C", @"D", nil];
for (NSUInteger i = 0; i < [array count]; i++)
{
    NSUInteger value = i+1;
    NSString* key = [array objectAtIndex:i];
    //Your code here.
}
andyvn22
  • 14,696
  • 1
  • 52
  • 74
0

In an NSDictionary your keys have to be unique. From the docs:

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:).

Once you have an NSDicitonary, you can gain access and loop through the keys using:

- (NSArray *)allKeys

EDIT:

to get similar functionality, check here

it sounds like it is what you are looking for Cheers,

Community
  • 1
  • 1
Stefan H
  • 6,635
  • 4
  • 24
  • 35
  • That doesn't help, because keys are not unique, so every time I ask for the value of a key, it returns the first occurrence. – aryaxt Mar 06 '12 at 21:54
  • I'm sorry, but NSDicitonarys do not have a way of storing dupicate keys. I'm looking for a solution that odesn't use a dictionary for you. – Stefan H Mar 06 '12 at 21:55
  • And it will always do the same – Victor Carmouze Mar 06 '12 at 21:56
  • 1
    @aryaxt The link I posted of using your dictionary, but having the value be and NSArray might be your best option. Hope it helps, Cheers! – Stefan H Mar 06 '12 at 22:09
0

If you add a key that already exists in an NSMutableDictionary, the dictionary itself will just overwrite the current key's value with the new value, and the old value won't exist any further

However, if you want to loop through the dictionary, check out this post:

looping through an NSMutableDictionary

Community
  • 1
  • 1
5StringRyan
  • 3,604
  • 5
  • 46
  • 69