// Create an NSDictionary dictionary object and fill it with some key/object pairs. Then make both
// mutable and immutable copies. Are these deep copies or shallow copies that are made? Verify your answer.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// Create object and key pairs to populate dictionary
NSMutableString *key1 = [NSMutableString stringWithFormat: @"First key"];
NSMutableString *key2 = [NSMutableString stringWithFormat: @"Second key"];
NSMutableString *key3 = [NSMutableString stringWithFormat: @"Third key"];
NSMutableString *obj1 = [NSMutableString stringWithFormat: @"First object"];
NSMutableString *obj2 = [NSMutableString stringWithFormat: @"Second object"];
NSMutableString *obj3 = [NSMutableString stringWithFormat: @"Third object"];
// Create dictionary and copies
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: obj1, key1, obj2, key2, obj3, key3, nil];
NSMutableDictionary *mutableDict;
NSDictionary *immutableDict;
mutableDict = [dict mutableCopy];
immutableDict = [dict copy];
// Change the first object and print dictionaries to see results
[obj1 setString: @"This isn't the same as it was before"];
NSLog(@"Original dictionary %@\n\n", dict);
NSLog(@"Mutable dictionary %@\n\n", mutableDict);
NSLog(@"Immutable dictionary %@\n\n", immutableDict);
NSLog(@"The first object in the dictionaries change when the original is changed therefore they are shallow copies.");
[mutableDict release];
[immutableDict release];
[pool drain];
return 0;
}
That's my code for the solution to the problem. As expected the copies are shallow.
One issue however, if I use the code
[key1 setString: @"A different key"];
in my program right where I change the object it's associated with, the key in the dictionary objects does not change the way I'd expect it to.
Is there some reason that a key cannot be changed while the objects can?