Ian Oswald
Ian Oswald

Reputation: 1375

Navigating multiple nested dictionaries in plist file

I have a .plist file that looks like this: alt text

and was wondering how I would go about navigating through the multiple dictionaries or if this is even the best way to set up the plist file.

Not all elements in the dictionary will have the same years or sizes associated with them so I'm not sure if arrays would be the way to go on it.

Upvotes: 1

Views: 3169

Answers (3)

Susha
Susha

Reputation: 37

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"DecisionName.plist"];
NSLog(@"Error in dictionary");
NSLog(@"HELLO");
NSMutableDictionary *plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];

NSArray *testChoice = [[NSArray alloc] initWithArray:[plistDict objectForKey:selectedDecision]];
self.choices = [testChoice objectAtIndex:0];
self.preferences = [testChoice objectAtIndex:1];

This code will be helpful which use to get values from plist having following structure......

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <array>
        <string>Toyota</string>
        <string>Honda</string>
    </array>
    <array>
        <string>Speed</string>
        <string>Reliability</string>
        <string>Price</string>
    </array>
</array>
</plist>

Upvotes: 0

slycrel
slycrel

Reputation: 4285

There is no "best way" that anyone can tell you. It depends on what you're doing and how you want to use the plist.

The standard way to do what you're talking about is to iterate through all of the keys in a for...in statement, similar to filipe's answer. If you know the "path" you want to traverse you can also use NSDictionary's [dict objectForKey:key] to get more direct access than looping through everything.

There's no magic here, just think of this kind of structure like an unordered tree. You have a list of items or "branches" and each item can itself be another branch, with a "leaf" or value node of the unordered tree at the end of a given traversal path.

Hope that helps some.

Upvotes: 2

filipe
filipe

Reputation: 3380

you can use the keyEnumerator property to go through all the keys in the dictionary, or you can simply use

for (NSString *key in myDict)
{
    ...
}

Upvotes: 1

Related Questions