views:

334

answers:

1

I know you could add all the keys to an array and add it to one side of the dictionary but I'm curious how you can add or insert a value at a certain point in the dictionary. The way i have it now it I believe it just keeps overwriting the last entries to make room for the new one:

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]);

heres the output:

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

+4  A: 

I'm surprised that code doesn't just crash. See here:

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

You are assigning to urlA twice and never assigning to urlB. Fix that and you'll see the correct value logged.

Note also that you can do this:

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

And see all of the key/value pairs in the dictionary.

bbum
Wow, I totally glossed over the second `urlA`. Good catch.
Chuck
He's also mixing `setValue:forKey:` with `setObject:forKey:`
Colin Gislason
ok that was what was happening, i think that makes sense let me go try and fix that and see what happens, thanks for the help.
nickthedude
when I did : NSLog(@"dictionary: %@", anNSDictionary);it logged:2010-01-13 11:44:26.785 assignment_1b[6170:a0f] { Apple = "http://www.apple.com"; "Stanford University" = "http://www.stanford.edu";}any idea why 'Apple' was not enclosed in quotes but all the other elements were?
nickthedude
@nickthedude: NSDictionary's description method doesn't put quotes around single words with no punctuation.
Chuck
NSDictionary's `description` method follows the quoting rules of old school pre-XML property lists...
bbum