NSMutableDictionary 的键值不打印

Value for key from NSMutableDictionary doesn't print

我正在向 Stephen Kochan 学习 "Programming in Objective-C",我对 NSDictionary 的可变副本有疑问。 所以,这是我的代码:

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]);
    }

你怎么看以及代码的结尾我正在打印我的 NSMutableDictionary 中的所有 key/values,但是对于 key 4 我没有值!

Screen from terminal

但是您如何看到 key 4 的值不为空!

[Content of NSMutableDictionary][2]

有什么问题吗?请帮忙

在最后的 for 循环中,您从 dictionary 而不是 dictionaryMutableCopy 获取值:

for (NSValue *key in [dictionaryMutableCopy allKeys]) {
    NSLog(@"Key: %@ value: %@", key, dictionaryMutableCopy[key]);
    //                               ^^^^^^^^^^^^^^^^^^^^^
}