As you know, arrays are indexed by a number; it is easy to ask “Give me object 10.” Dictionaries are indexed by a string; it is easy to ask “Give me the object stored under the key favoriteColor.” More precisely, a dictionary is a collection of key-value pairs. The key is typically a string, and the value can be any sort of object. These key-value pairs are not kept in any particular order.
Let’s make a dictionary of executives. The key will be an executive title, and the value will be an instance of Employee. The first employee will be put in the dictionary under @"CEO"; the second under @"CTO". Change your main.m to create and populate the NSMutableDictionary. Then, print out the dictionary of executives. Finally, set the pointer to the dictionary to nil so that you can see the dictionary being deallocated.
// Create an array of Employee objects NSMutableArray *employees = [[NSMutableArray alloc] init]; // Create a dictionary of executives NSMutableDictionary *executives = [[NSMutableDictionary alloc] init]; for (int i = 0; i < 10; i++) { // Create an instance of Employee Employee *person = [[Employee alloc] init]; // Give the instance variables interesting values [person setWeightInKilos:90 + i]; [person setHeightInMeters:1.8 - i/10.0]; [person setEmployeeID:i]; // Put the employee in the employees array [employees addObject:person]; // Is this the first employee? if (i == 0) { [executives setObject:person forKey:@"CEO"]; } // Is this the second employee? if (i == 1) { [executives setObject:person forKey:@"CTO"]; } } … NSLog(@"allAssets: %@", allAssets); NSLog(@"executives: %@", executives); executives = nil; NSPredicate *predicate = [NSPredicate predicateWithFormat: @"holder.valueOfAssets > 70"]; NSArray *toBeReclaimed = [allAssets filteredArrayUsingPredicate:predicate]; NSLog(@"toBeReclaimed: %@", toBeReclaimed); toBeReclaimed = nil; NSLog(@"Giving up ownership of arrays"); allAssets = nil; employees = nil; } return 0; }
Build and run the program. The executives dictionary should log itself out:
executives = { CEO = "<Employee 0: $0 in assets>"; CTO = "<Employee 1: $153 in assets>"; }