Friday, 11 January 2013

Read data from a plist

I am learning iPhone development these days. I need to read data from a plist file into NSArray

Creating a plist

My plist (ClothesArray.plist) is shown as below. It is a little bit complex. There are two dictionaries: US and JP. In each dictionary, it includes a clothes array.
<plist version="1.0">
<dict>
    <key>US</key>
    <dict>
        <key>Clothes</key>
        <array>
            <string>ABC</string>
            <string>DEF</string>
        </array>
     </dict>
     <key>JP</key>
     <dict>
        <key>Clothes</key>
        <array>
            <string>AAA</string>
            <string>XXX</string>
        </array>
     </dict>
</dict>
</plist>

Reading from a plist
What I need is to get the clothes array in each dictionary.

    //Get the path of the plist
    NSString *path = [[NSBundle mainBundle] pathForResource:@"ClothesArray" ofType:@"plist"];
    //Build the Dictionary from the plist
    NSMutableDictionary * dict =  [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    //Get the array by key from the plist
    NSMutableArray *clothesUSMutableArray = [[dict objectForKey:@"US"] objectForKey:@"Clothes"];
     NSMutableArray *clothesJPMutableArray = [[dict objectForKey:@"JP"] objectForKey:@"Clothes"];
    //print
    for(NSString *str in clothesUSMutableArray){
     NSLog(@"%@", str);
    }
Now, I can get the data from the plist into NSArray.