NSDictionary
Create
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
or
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:keys];
or using appropriate literal syntax
NSDictionary *dict = @{@"key": @"value", @"nextKey": @"nextValue"};
NSDictionary to NSArray
NSDictionary *myDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
NSArray *copiedArray = myDictionary.copy;
Get keys:
NSArray *keys = [myDictionary allKeys];
Get values:
NSArray *values = [myDictionary allValues];
NSDictionary to NSData
NSDictionary *myDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];
Reserve path:
NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];
NSDictionary to JSON
NSDictionary *myDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
NSMutableDictionary *mutableDictionary = [myDictionary mutableCopy];
NSData *data = [NSJSONSerialization dataWithJSONObject:myDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
Block Based Enumeration
Enumerating dictionaries allows you to run a block of code on each dictionary key-value pair using the method enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))block
Example:
NSDictionary stockSymbolsDictionary = @{
@"AAPL": @"Apple",
@"GOOGL": @"Alphabet",
@"MSFT": @"Microsoft",
@"AMZN": @"Amazon"
};
NSLog(@"Printing contents of dictionary via enumeration");
[stockSymbolsDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"Key: %@, Value: %@", key, obj);
}];
Fast Enumeration
NSDictionary
can be enumerated using fast enumeration, just like other collection types:
NSDictionary stockSymbolsDictionary = @{
@"AAPL": @"Apple",
@"GOOGL": @"Alphabet",
@"MSFT": @"Microsoft",
@"AMZN": @"Amazon"
};
for (id key in stockSymbolsDictionary)
{
id value = dictionary[key];
NSLog(@"Key: %@, Value: %@", key, value);
}
Because NSDictionary
is inherently unordered, the order of keys that in the for loop is not guaranteed.