为什么我的NSMutableDictionary在setObject中变为null?

时间:2011-11-20 23:11:04

标签: iphone objective-c ios ios4

我正在尝试此代码,

 NSString *titleOfPlace = [place objectForKey:@"name"];
 NSString *reference = [place objectForKey:@"reference"];
 [placesExtraInfo setObject:reference forKey:titleOfPlace];
 NSLog(@"%@", (NSString *)[placesExtraInfo objectForKey:titleOfPlace]);

输出是,

2011-11-21 10:06:49.536 Tittle-Tattle[25545:1bb03] 0
2011-11-21 10:06:49.554 Tittle-Tattle[25545:1bb03] (null)
2011-11-21 10:06:49.555 Tittle-Tattle[25545:1bb03] (null)
2011-11-21 10:06:49.555 Tittle-Tattle[25545:1bb03] (null)
2011-11-21 10:06:49.555 Tittle-Tattle[25545:1bb03] (null)
.... about 20 of them as I had 20 objects to add...

我做错了什么?

PS 当我记录titleOfPlacereference的NSlog值时,它的打印完美。为什么它没有被保存在NSMutableDictionary中?

感谢您提供任何意见!

更新

title John's Grill
reference CnRkAAAAmyHKGYtr9brX5uJEwlyK791oCWErzrY8hKjFX2eXBV5hrrbVjE_-CPvCfoxUpu4TiXswTXUtvP_UkYG2p4RG2a1oc_4HSxku1jIlVx0H4LZgo_SQbUMSrJ1xDvwxxWVsyWtEjxCIF6qma_slsFSLphIQmSnwBgYQATX46MXkuW0s5BoUGM0K_KRvH_gbc4k-TSsSpgnQyTk
please no null (null)
2011-11-21 10:19:40.339 Tittle-Tattle[30277:1bb03] title Fifth Floor
reference CnRiAAAAtzTFHqqcAMyYzuKSq7nwHdt9e-lnP1W4i6pyUGQiomT0SvqDm1RWxhH05fJpqMJ9RdU8QHO-g7-EXgVHQnoms_bip5gGXdE96SCN7HQW5-Y69K7144VvgnOATVVNZRWQgyNZ2NNYRSltVuL61UXg7BIQ8YinfdZ6Ahq2lU6XhNVQ7hoU2IwUAHKcGHELPeYgbshPmiS9nOA
please no null (null)
2011-11-21 10:19:40.339 Tittle-Tattle[30277:1bb03] title Ghirardelli Chocolate
reference CnRsAAAAkHnx_nYhhe4QnV2jQyWdU5Vb387rFdVlhPcsnp6ZUjEroEzRLCcYO687ybSlTqSMDP5BxJVeehgUt9kkL97l1puos89e2HT85t-H5VWl7G0qZ0M_IoL0Gp3VmKl07MQRFt0_zdXesSVjSzLFRpBDChIQwcpeapYjGYq8jSQTZUmoMxoUSS1M0rBvMkqKSRRGMpWlyWbHUJ0
please no null (null)

3 个答案:

答案 0 :(得分:2)

我认为albertamg是对的 - 检查placesExtraInfo。您的问题仅表明您已查看titleOfPlacereference。尝试将nil对象存储到字典中会引发异常,但向nil发送任何消息会导致nil

答案 1 :(得分:2)

albertamg正在做点什么。

您无法设置nil值,也无法将nil值设置为nil键

//given
NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
//will crash here
[dict setObject:nil forKey:@"key"];
//will crash here if the above line is commented out
[dict setObject:@"val" forKey:nil];

然而,

 NSLog(@"%@", [nil objectForKey:@"key"]);

输出

2011-11-20 18:22:08.609 TestEnvironment[1221:207] (null)

答案 2 :(得分:2)

正如我在上面的评论中所说,请确保placesExtraInfo nil(如果您将objectForKey:发送到nil,它将会返回nil)。