PDA

View Full Version : Getting the name of a key from a NSDictionary


LongJumper
2005.08.13, 04:50 AM
I set up an enumerator on a dictionary, then as I go through, I want the actual names of those keys... not finding the right function for this anywhere. Let me know.

willThimbleby
2005.08.13, 06:18 AM
Enumerate on the keys [dict allKeys] then access the objects, or for each object get its keys [obj allKeysForObject]

Fenris
2005.08.13, 06:22 AM
If you're only looking for the keys in the directory, check out [NSDirectory keyEnumerator]. There is also [NSDirectory allKeys]Â*that returns an array of NSStrings with all the keys.

LongJumper
2005.08.13, 06:48 AM
Erm, maybe I wasn't clear. I have a property list, under it's root it has from 1 to n keys, at which I don't know at compile time.

So say the plist looks like this:
Root:
MyFirstEntry: with more keys embedded inside it
MySecondEntry: with mroe keys embedded inside it
Timmy: with more keys embedded inside it.

I set up my enumerator like so:

NSEnumerator* keyList = [jobData objectEnumerator];
id group;
while((group = [keyList nextObject]))
{
NSDictionary* dict = (NSDictionary*)group;

//Put this string in the job name...
//NSString* s = [dict stringValue];
//[groupName setStringValue:s];

//Put the job count up
int howManyJobs = [[dict objectForKey:@"jobList"] count];
if(howManyJobs != 1)
[groupJobCount setStringValue:[NSString stringWithFormat:@"%d jobs...", howManyJobs]];
else
[groupJobCount setStringValue:[NSString stringWithFormat:@"%d job...", howManyJobs]];
}


Now, I want to know the name of the key I am currently getting from the enumerator. My futile attempt is the [dict stringValue], but I knew that wouldn't work. Basically, I want to know what that dictionary is called in my plist, so later I could use that name for objectForKey:dictionaryName.

So it'd give me my MyFirstEntry, then MySecondEntry, then Timmy.

Cochrane
2005.08.13, 08:28 PM
If you apply the suggestions above to this code, you'll get the following

NSEnumerator* keyList = [jobData keyEnumerator];
id groupKey;
while((groupKey = [keyList nextObject]))
{
NSString* key = (NSString *)groupKey;
NSDictionary* dict = [jobData objectForKey:key]

//Put this string in the job name...
//NSString* s = [dict stringValue];
//[groupName setStringValue:s];

//Put the job count up
int howManyJobs = [[dict objectForKey:@"jobList"] count];
if(howManyJobs != 1)
[groupJobCount setStringValue:[NSString stringWithFormat:@"%d jobs...", howManyJobs]];
else
[groupJobCount setStringValue:[NSString stringWithFormat:@"%d job...", howManyJobs]];
}

So you would be enumerating the keys, then getting the dictionary with the keys, and in this example you have the key in the variable named key.