0

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

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

4

1 回答 1

5

我很惊讶代码不只是崩溃。看这里:

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

您分配给 urlA 两次,从不分配给 urlB。修复它,您将看到记录的正确值。

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

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

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

于 2010-01-13T19:16:47.467 回答