【问题标题】:Value for key from NSMutableDictionary doesn't printNSMutableDictionary 中的键值不打印
【发布时间】:2016-02-05 10:10:33
【问题描述】:

我正在向 Stephen Kochan 学习“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 4,我没有值!

Screen from terminal

但是你怎么能看到key 4 的值不为空!

[Content of NSMutableDictionary][2]

有什么问题?请帮忙

【问题讨论】:

    标签: objective-c xcode nsdictionary nsmutabledictionary nslog


    【解决方案1】:

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

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

    【讨论】:

    • 哦,非常感谢!我知道这将是一个愚蠢的错误!
    • @NikitaBonachev BTW 使用 NSValue 对我来说是不寻常的。我从来没有用过它;如果您知道键是字符串,那么使用NSString 是正常的。我猜您正在学习教程,但请记住这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    相关资源
    最近更新 更多