问题
I have a plist, with main NSDictionary, in which its keys are dates. For every date, I have a NSDictionary in which the keys are (let's say) categories. Every Category holds Keys and values.
I would like to create 2 variables that each will hold the correct NSDictionary:
NSDictionary *dates = ?
NSDictionary *Categories = ?
Below is my plist, please help to understand how this should be done.
**Note: I do know how to assign the first dates dictionary from the plist... just stuck with the Categories.
NSDictionary *dict = [[NSDictionary alloc]initWithContentsOfFile:path];
self.dates = dict;
[dict release];
The plist:
<dict>
<key>2010-05-08</key>
<dict>
<key>Catergory1</key>
<dict>
<key>key1</key>
<string>value1</string>
<key>key2</key>
<string>value2</string>
<key>key3</key>
<string>value3</string>
</dict>
<key>Catergory2</key>
<dict>
<key>key1</key>
<string>value1</string>
<key>key2</key>
<string>value2</string>
<key>key3</key>
<string>value3</string>
</dict>
<key>2010-01-02</key>
<dict>
<key>Catergory1</key>
<dict>
<key>key1</key>
<string>value1</string>
<key>key2</key>
<string>value2</string>
<key>key3</key>
<string>value3</string>
</dict>
<key>Catergory2</key>
<dict>
<key>key1</key>
<string>value1</string>
<key>key2</key>
<string>value2</string>
<key>key3</key>
<string>value3</string>
</dict>
</dict>
</dict>
</plist>
Any help would be greatly appreciated, as I've searched over the forum's history and found nothing that matches my scenario.
THANKS!
回答1:
You should markup the values as arrays, so you can simply iterate over them.
<plist version="1.0">
<dict>
<key>dates</key>
<array>
<dict>
<key>date</key>
<date>2010-05-17T12:40:32Z</date>
<key>categories</key>
<array>
<dict>
<key>key</key>
<string>value</string>
</dict>
<dict>
<key>key</key>
<string>value</string>
</dict>
</array>
</dict>
<dict>
<key>date</key>
<date>2010-05-17T12:40:32Z</date>
<key>categories</key>
<array>
<dict>
<key>key</key>
<string>value</string>
</dict>
<dict>
<key>key</key>
<string>value</string>
</dict>
</array>
</dict>
</array>
</dict>
</plist>
Code:
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:pathToFile];
for (NSDictionary *date in [dict valueForKey:@"dates"]) {
NSArray *catgories = [date valueForKey:@"categories"];
}
来源:https://stackoverflow.com/questions/2848340/nested-nsdictionary-from-plist