kindaran
kindaran

Reputation: 511

Accessing elements from a Dictionary plist

I'm trying to make use of a dictionary plist as shown below: alt text

I read it into a temp dictionary just fine.

What I'd like to know is if there is an easy way to get at the string children (which are actually a single element in an array, as you can see).

I initially tried objectAtIndex but that was, of course, returning an array, not the string value. I next tried using an NSEnumerator (an objectEnumerator) and then use objectAtIndex:0 to get me the string which does work.

But I'm really hoping there is an easier way to do that.

Edit: clarifying what I'm trying to do.

I want to use the key values (e.g. "All Items") to populate a tableview cell.text and then use the string values (e.g. "find.png") in order to help populate cell.image via UIImage imageNamed:. I would prefer NOT to use hard-coded values (such as objectForKey:@"All Items") so that I can change the data in the plist without also making code changes.

Upvotes: 1

Views: 5538

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

Alexandre L Telles
Alexandre L Telles

Reputation: 3435

You can use the fast enumeration of the dictionary:

for (id key in dict) {
    NSArray *array = [dict objectForKey:key];
    NSLog(@"key: %@, value: %@", key, [array objectAtIndex:0]);
}

Upvotes: 0

Marc Charbonneau
Marc Charbonneau

Reputation: 40517

You need to call objectForKey: on the dictionary to get one of the arrays, and then call objectAtIndex:0 (or just lastObject) on the array to get the string. You can combine these two method calls into one line of code, for example:

[[dictionary objectForKey:@"All Items"] lastObject];

Upvotes: 2

Related Questions