PDA

View Full Version : Help with NSMutableDicitonary




Glama
Jul 26, 2009, 10:46 AM
Hi,
I'm trying to understand code in a development book thats related to mutable dictionaries. The author creates an array of NSMutableDictionary items like this:


self.menuList = [[NSMutableArray alloc] init];
[menuList release];
[menuList addObject:[NSMutableDictionary
dictionaryWithObjectsAndKeys:
NSLocalizedString(@"London", @"City Section"),
kSelectKey,
NSLocalizedString(@"US dollars to pounds",
@"City Explain"), kDescriptKey,
nil,kControllerKey, nil]];


In trying to dissect the line, I consulted the documentation for NSMutableDictionary. But it lists the methods for adding entries to the dictionary as
setObject:forKey:
setValue:forKey:
addEntriesFromDictionary:
setDictionary:

Since I dont see any of those in the code, Im confused. I know a dictionary is supposed to match keys with values, so I dont know why there seem to be "extra" terms in the line.

Phil



Cinder6
Jul 26, 2009, 11:33 AM
NSMutableDictionary +dictionaryWithObjectsAndKeys: takes an array or a null-terminated multi-argument list of objects and keys. It goes in the order "object, key, object, key, ..., nil". Looking at it, though, it seems like there's an extra 'nil' in there, which suggests to me it'll never add the kControllerKey key (which has no associated object).

Then again, maybe I'm wrong with how it parses the array, and it keeps going until the last occurrence of nil.

Glama
Jul 26, 2009, 12:07 PM
NSMutableDictionary +dictionaryWithObjectsAndKeys: takes an array or a null-terminated multi-argument list of objects and keys. It goes in the order "object, key, object, key, ..., nil". Looking at it, though, it seems like there's an extra 'nil' in there, which suggests to me it'll never add the kControllerKey key (which has no associated object).

Then again, maybe I'm wrong with how it parses the array, and it keeps going until the last occurrence of nil.

I looked up dictionaryWithObjectsAndKeys and I see what youre saying. The code doesnt look right (even though it seems to work) but now i know a bit more about dictionaryWithObjectsAndKeys. Thanks.

Cinder6
Jul 26, 2009, 12:32 PM
What doesn't look right? If it's the call to NSLocalizedString(), note that it's a function that returns an NSString object, so it's fine to use in the arguments for +dictionaryWithObjectsAndKeys:.