IPhone Objects from NSDictionary PList

in my application I have a section where I boot from a saved plist that has 2 nested dictionaries like this:

<?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"> <dict> <key>1</key> <dict> <key>color</key> <string>yellow</string> <key>lang</key> <string>US</string> <key>name</key> <string>Peter</string> <key>uid</key> <string>1</string> </dict> <key>2</key> <dict> <key>color</key> <string>blue</string> <key>lang</key> <string>US</string> <key>name</key> <string>Josh</string> <key>uid</key> <string>2</string> </dict> <key>3</key> <dict> <key>color</key> <string>red</string> <key>lang</key> <string>DE</string> <key>name</key> <string>Susan</string> <key>uid</key> <string>3</string> </dict> </dict> </plist> 

Now I want to access the string as an external dictionary from key 2, the value for the color of the internal key (blue) I tried to make 2 loops, and it works for the external dictionary, but I can not access the internal

 NSMutableDictionary *savedData = [NSMutableDictionary dictionaryWithContentsOfFile:path]; // This contains all data from plist for (int x=0; x<[savedData count]; x++) { NSString *itemNumber = [NSString stringWithFormat:@"%d", x+1]; //This prints out the correct inner dictionary NSLog(@"item#%@: %@",itemNumber,[savedData objectForKey:itemNumber]); for (NSDictionary *dict in [savedData objectForKey:itemNumber]) { //prints out color, lang, uid, but no key-value pairs NSLog(@"dict: %@",dict); } } 

I would like to know how to directly access key value pairs inside the internal dictionary, can someone give me a hit in the right direction, please?

+4
source share
3 answers

How about this:

 NSString *blueColorString = [[savedData objectForKey:@"2"] objectForKey:@"color"]; 

The trick is to nest the method calls, the first of them [savedData objectForKey: 2] returns you an internal dictionary, on which you can call the method again. Hope this works as intended.

Best Robin

+3
source

NSLog(@"%@", [savedData valueForKeyPath:@"1.color"]);

yellow

+1
source

Typically, you use valueForKey: when your keys are strings:

 // to get to "blue" string NSLog(@"outer key '2', inner key 'color' = %@",[[savedData valueForKey:@"2"] valueForKey:@"color"]); // all inner key / value pairs for (NSString *key in savedData) { NSDictionary *innerDict = [savedData valueForKey:key]; for (NSString *innerKey in innerDict) { NSLog(@"key %@ value %@",innerKey,[innerDict valueForKey:innerKey]); } } 
0
source

All Articles