Reputation: 327
I'm learning "Programming in Objective-C" from Stephen Kochan and I have a problem with a mutable copy of NSDictionary
.
So, here is my code:
NSMutableString *value1 = [[NSMutableString alloc ] initWithString: @"Value for Key one" ];
NSMutableString *value2 = [[NSMutableString alloc ] initWithString: @"Value for Key two" ];
NSMutableString *value3 = [[NSMutableString alloc ] initWithString: @"Value for Key three" ];
NSMutableString *value4 = [[NSMutableString alloc ] initWithString: @"Value for Key four" ];
NSString *key1 = @"key1";
NSString *key2 = @"key2";
NSString *key3 = @"key3";
NSString *key4 = @"key4";
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: value1, key1, value2, key2, value3, key3, nil];
NSDictionary *dictionaryCopy = [[NSDictionary alloc] init];
NSMutableDictionary *dictionaryMutableCopy = [[NSMutableDictionary alloc] init];
dictionaryCopy = [dictionary copy];
dictionaryMutableCopy = [dictionary mutableCopy];
[value1 setString: @"New value for Key one" ];
[value2 setString: @"New value for Key two" ];
[value3 setString: @"New value for Key three" ];
dictionaryMutableCopy[key4] = value4;
NSLog(@"All key for value 4");
for (NSValue *key in [dictionaryMutableCopy allKeysForObject:value4]) {
NSLog(@"key: %@", key);
}
NSLog(@"All values");
for (NSValue *val in [dictionaryMutableCopy allValues]) {
NSLog(@"value: %@", val);
}
for (NSValue *key in [dictionaryMutableCopy allKeys]) {
NSLog(@"Key: %@ value: %@", key, dictionary[key]);
}
How you see and the end of the code I'm printing all key/values from my NSMutableDictionary
, but for key 4
I haven't a value!
But how you can see the value for key 4
is't null!
[Content of NSMutableDictionary][2]
What's the problem? Please help
Upvotes: 1
Views: 345
Reputation: 122381
In the final for
loop, you are getting the value from dictionary
instead of dictionaryMutableCopy
:
for (NSValue *key in [dictionaryMutableCopy allKeys]) {
NSLog(@"Key: %@ value: %@", key, dictionaryMutableCopy[key]);
// ^^^^^^^^^^^^^^^^^^^^^
}
Upvotes: 2