0

I have a simple UITableView, when users adds new rows, these will be added to the NSMutableDictionary. I can retrieve the values for a specific key.

NSArray *myArr = [myDictionary valueForKey:@"Food"];

This will show me all values for key food, this is an example of my NSLog:

( burger, pasta )

If I add more objects to myDictionary but for a different key, for example:

NSArray *drinks = [NSArray arrayWithObjects:@"cola",@"sprite",nil];
[myDictionary setObject:drinks forKey:@"Drink"];

I can't retrieve all values using the following code:

NSArray *allMenu = [myDictionary allValues];

It shows me the following NSLog:

( ( burger, past ), ( cola, sprite ) )

I don't know where is the problem. Why I can't get all values from NSDictionary to NSArray.

If I use the code:

NSArray *allMenu = [[myDictionary allValues] objectAtIndex:0];

will show me the Food values. If I change objectAtIndex to 1 will show me the Drink value.

Mihir Oza
  • 2,768
  • 3
  • 35
  • 61

3 Answers3

4

I am not entirely sure what you are asking, if you are trying to print all of the values within an NSDictionary do the following:

//Gets an array of all keys within the dictionary
NSArray dictionaryKeys = [myDictionary allKeys];
for (NSString *key in dictionaryKeys)
{
    //Prints this key
    NSLog(@"Key = %@", key);
    //Loops through the values for the aforementioned key
    for (NSString *value in [myDictionary valueForKey:key])
    {
        //Prints individual values out of the NSArray for the key
        NSLog(@"Value = %@", value);
    }
}
Lachlan
  • 312
  • 2
  • 15
1

You can do this in one line by flattening the returned 2-dimensional array by using key value coding (KVC). I found this in another answer, see the docs. In your case, it looks as follows:

NSMutableDictionary *myDictionary = [NSMutableDictionary dictionary];
NSArray *food = [NSArray arrayWithObjects:@"burger",@"pasta",nil];
[myDictionary setObject:food forKey:@"Food"];
NSArray *drinks = [NSArray arrayWithObjects:@"cola",@"sprite",nil];
[myDictionary setObject:drinks forKey:@"Drink"];

NSArray *allMenue = [[myDictionary allValues] valueForKeyPath:@"@unionOfArrays.self"];
Community
  • 1
  • 1
Reinhard Männer
  • 14,022
  • 5
  • 54
  • 116
0

Try this Solution :

- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array 
        {
          id objectInstance;
          NSUInteger indexKey = 0U;
          for (objectInstance in myArr)
            [mutableDictionary setObject:objectInstance forKey:[NSNumber numberWithUnsignedInt:indexKey++]];

          return (NSDictionary *)[myDictionary autorelease];
        }
Mihir Oza
  • 2,768
  • 3
  • 35
  • 61