Working with NSDictionary and NSMutableDictionary in Foundation Framework
NSDictionary Overview
NSDictionary provides key-value storage where each unique key maps to a corresponding value. Unlike mutable variants, NSDictionary instances are immutable after initialziation.
Creating NSDictionary
// Empty dictionary
NSDictionary *emptyDict = [NSDictionary dictionary];
// Single key-value pair
NSDictionary *singlePair = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
// Multiple key-value pairs
NSDictionary *multiPair = @{@"key1": @"value1", @"key2": @"value2"};
Basic Operations
// Count elements
NSUInteger count = [dictionary count];
// Retrieve value
id value = [dictionary objectForKey:@"key"];
Iterating Through NSDictionary
// Fast enumeration
for (NSString *key in dictionary) {
id value = dictionary[key];
NSLog(@"%@ => %@", key, value);
}
// Block enumeration
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"%@ => %@", key, obj);
}];
File Operations
// Write to file
[dictionary writeToFile:@"/path/to/file.plist" atomically:YES];
// Read from file
NSDictionary *readDict = [NSDictionary dictionaryWithContentsOfFile:@"/path/to/file.plist"];
NSMutableDictionary Basics
NSMutableDictionary extends NSDictionary with mutability, allowing dynamic modification of contents after creation.
Common Mutating Methods
// Add/modify value
[mutableDict setObject:@"newValue" forKey:@"key"];
// Remove value
[mutableDict removeObjectForKey:@"key"];
// Clear all
[mutableDict removeAllObjects];
Dictionary vs Array Comparison
Key differences:
- NSArray maintains order, NSDictionary doesn't
- Arrays use indices, dictionaries use keys
// Array example
NSArray *array = @[@"item1", @"item2"];
id item = array[0];
// Dictionary example
NSDictionary *dict = @{@"key1": @"value1", @"key2": @"value2"};
id value = dict[@"key1"];