ram2013 ram2013 - 3 months ago 27
iOS Question

How to read Array from plist iOS

I am trying to read plist which contains array

<?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>key1</key>
<string>value1</string>
<key>key2</key>
<string>value2</string>
<key>keyarray1</key>
<array>
<string>keyitem1</string>
<string>keyitem2</string>
</array>
</dict>
</plist>


when i try to read valueForKey:@"keyarray1", I get null value.
I tried to read as a string and array nut no use.

My Code

NSDictionary * values=[[NSDictionary alloc] initWithContentsOfFile:@"values.plist"];
NSArray *arrayValues=[[NSArray alloc] initWithArray:[values valueForKey:@"keyarray1"]];

Answer

First of all Check your plist looks like:

enter image description here

Now write following lines where you are accessing your plist

Objectiv C:

NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Values" ofType:@"plist"]];
NSLog(@"dictionary = %@", dictionary);
NSArray *array = [dictionary objectForKey:@"keyarray1"];
NSLog(@"array = %@", array);

Swift:

let path = NSBundle.mainBundle().pathForResource("Values", ofType:"plist")
let dictionary = NSDictionary(contentsOfFile:path)
let array = dictionary["keyarray1"] as Array<String>

Here is the complete screen shot (with log output) of my work window:

enter image description here