2016-02-05 67 views
1

我正在學習Stephen Kochan的「Objective-C編程」,我遇到了NSDictionary的可變副本問題。 所以,這裏是我的代碼:來自NSMutableDictionary的鍵的值不打印

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] 

什麼問題?請幫助

回答

2

在最後for循環,你是從dictionary而不是dictionaryMutableCopy所獲得的價值:

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

哦,非常感謝!我知道這將是一個愚蠢的錯誤! –

+0

@NikitaBonachev使用'NSValue'的BTW對我而言並不常見。我從來沒有用過它;如果你知道鍵是字符串,那麼使用'NSString'是正常的。我想你正在學習一個教程,但請牢記這一點。 – trojanfoe

+0

好的,感謝您的解決方案和建議。 –