Retrieve All Keys And Values Of An NSDictionary Object

Wed, Mar 27

If you ever need to collect all the values or all the keys of an NSDictionary object, there are methods in the dictionary class to provide the information as shown below.

Let’s start with a simple dictionary that contains three objects, an array, a string and a number:

// Create array
NSArray *array = [NSArray arrayWithObjects:
  @"String 1",
  [NSNumber numberWithInteger:99],
  [NSArray arrayWithObjects:
             @"array value 1",
             @"array value 2",
             nil],
  nil];
 
// Using literal style, add three objects
NSDictionary *dictionary = @{@"arrayKey" : array,
                             @"numberKey" : [NSNumber numberWithInt:25],
                             @"stringKey" : @"String value"};
 
NSLog(@"dictionary: %@", dictionary);

The dictionary looks as follows:

dictionary: {
    arrayKey =     (
        "String 1",
        99,
                (
            "array value 1",
            "array value 2"
        )
    );
    numberKey = 25;
    stringKey = "String value";
}

The dictionary class provides a method to store all the keys into an NSArray. The code below creates an array of keys and outputs the same to the console:

NSArray *arrayOfKeys = [dictionary allKeys];
NSLog(@"Keys: %@", arrayOfKeys);

The output is below:

Keys: (
    numberKey,
    stringKey,
    arrayKey
)

In a similar manner you can populate an array with all the values from the dictionary:

NSArray *arrayOfValues = [dictionary allValues];
NSLog(@"Values: %@", arrayOfValues);

The output follows:

Values: (
    25,
    "String value",
        (
        "String 1",
        99,
                (
            "array value 1",
            "array value 2"
        )
    )
)

Leave a Comment