开发者

Nested Dictionary - Targeting Individual Keys

I appreciate there are lots of this type of question around here but I've not been able to find a feasible answer.

Put simply, I need to get an array of Prices for all products within a chosen category.

Here is my pList:

<key>Product Category</key>
    <dict>
        <key>Product 1</key>
        <dict>
            <key>Image</key>
            <string></string>
            <key>Large Image</key>
            <string></string>
            <key>Detail</key>
            <string></string>
            <key>Price</key>
            <integer>100</integer>
        </dict>
        <key>Product 2</key>
        <dict>
            <key>Image</key>
            <string></string>
            <key>Large Image</key>
            <string></string>
            <key>Detail</key>
            <string></string>
            <key>Price</key>
            <integer>200</integer>
        </dict>
    </dict>

I have no idea how to target deep within a hierarchy like this. Here is my attempt so far:

NSString *detailPListPath = [[NSBundle mainBundle] pathForResource:@"detail" ofType:@"plist"];
NSDictionary *d开发者_高级运维etailDictionary = [NSDictionary dictionaryWithContentsOfFile:detailPListPath];
currentDetail = [[NSMutableArray alloc] init];

for (id object in [detailDictionary objectForKey:indication]) {
    [currentDetail addObject:object];
}

But then currentDetail just shows Product 1, Product 2 etc.

Thanks for any help you can offer!


currentDetail just shows Product 1, Product 2 etc.

Since fast enumeration of a NSDictionary iterates over the keys, you are adding the keys to the array. Hence, your output shows Product 1, Product 2, etc.

I need to get an array of Prices for all products within a chosen category.

You need to use these keys (Product 1, Product 2, etc.) to retrieve the associated product dictionary and then retrieve the value associated with the Price key:

NSDictionary *detailDict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"detail" ofType:@"plist"]];
NSDictionary *categoryDict = [detailDict objectForKey:@"Product Category"];
NSMutableArray *pricesArray = [NSMutableArray arrayWithCapacity:[categoryDict count]];
for (NSString *key in categoryDict) {
    [pricesArray addObject:[[categoryDict objectForKey:key] objectForKey:@"Price"]];
}

Bear in mind that the resulting pricesArray is in no specific order.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜