views:

120

answers:

1

I have a plist file that I am loading into an NSDictionary *setDictionary that contains a set of fields, pictureDesc1, pictureDesc2, etc.

Once the NSDictionary is loaded, I can retrieve a value using

[setDictionary objectForKey:@"pictureDesc1"];

But I cannot do a loop like this:

for (int i=1; i<=numberOfPictures; i++) {
    NSString *keyName = [NSString stringWithFormat:@"pictureDesc%d",i];
    NSString *description = [NSString stringWithFormat:@"%@", [setDictionary objectForKey:keyName]];
}

Is there a different way to dynamically call keys from within an NSDictionary?

+1  A: 

If you keys fit a numerical pattern, then it would be easier and more robust to simply store them in a array. You could even store an array as a value in the dictionary with the key of "pictureDescription".

Then when you wanted to loop through them just use a simple numerical loop:

NSArray *pictArray=[setDictionary valueForKey:@"pictureDescription"];
NSString *description;
for (i=0;i<[pictArray count];i++){
    description=[pictArray objectAtIndex:i];
    //... do whatever
}

If you find yourself shoehorning the functionality of an array into a dictionary or vice versa you probably should back out and just use an array or dictionary in the first place. When using a dictionary, just use an enumerator to step through the values.

TechZen
Thanks! That worked!
jud
Don't forget to hit the checkmark next to the correct answer. It lets the system know the question has been answered and bumps up your acceptance rate.
TechZen