如何在不使用数组的情况下向NSMutableDictionary添加多个键和值?

时间:2010-01-13 19:01:32

标签: objective-c nsmutabledictionary key-value

我知道您可以将所有键添加到数组中并将其添加到字典的一侧但我很好奇如何在字典中的某个点添加或插入值。我现在拥有它的方式我相信它会一直覆盖最后的条目以便为新的条目腾出空间:

NSMutableDictionary *bookmarks = [[NSMutableDictionary alloc] init];
NSString *keyA = @"Stanford University";
NSString *keyB = @"Apple";
NSString *keyC = @"cs193p.com";
NSString *keyD = @"Stanford on iTunes";
NSString *keyE = @"Stanford Mail";
NSString *surlA = @"http://www.stanford.edu";
NSString *surlB = @"http://www.apple.com";
NSString *surlC = @"http://www.cs193p.stanford.edu";
NSString *surlD = @"http://www.itunes.stanford.edu";
NSString *surlE = @"http://www.stanfordshop.com";

NSURL  *urlA;
urlA = [NSURL URLWithString:surlA]; 
NSURL  *urlB;
urlA = [NSURL URLWithString:@"http://www.apple.com"]; 


[bookmarks setValue:urlA forKey: keyA];
[bookmarks setObject:urlB forKey: keyB];
//[bookmarks setObject:urlC forKey: keyC];
//[bookmarks setObject:urlD forKey: keyD];
//[bookmarks setObject:urlE forKey: keyE];

 NSLog(@"%@", [bookmarks valueForKey:keyA]);

继承人的输出:

2010-01-13 11:08:51.484 assignment_1b [6035:a0f] http://www.apple.com

1 个答案:

答案 0 :(得分:5)

我很惊讶代码不会崩溃。见这里:

NSURL  *urlA;
urlA = [NSURL URLWithString:surlA]; 
NSURL  *urlB;
urlA = [NSURL URLWithString:@"http://www.apple.com"]; 

您分配给urlA两次,从未分配给urlB。修复此问题,您将看到记录的正确值。

另请注意,您可以这样做:

NSLog(@"dictionary: %@", anNSDictionary);

查看字典中的所有键/值对。