user5568766
user5568766

Reputation:

Get all values from NSMutableDictionary

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.

Upvotes: 0

Views: 3693

Answers (3)

Reinhard Männer
Reinhard Männer

Reputation: 15217

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

Upvotes: 1

Mihir Oza
Mihir Oza

Reputation: 2796

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

Upvotes: 0

Lachlan
Lachlan

Reputation: 312

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);
    }
}

Upvotes: 4

Related Questions