ram2013
ram2013

Reputation: 505

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"]];

Upvotes: 26

Views: 41640

Answers (6)

Jack
Jack

Reputation: 14329

Swift 4

As in Swift 4 you can use codable & PropertyListDecoder

func setData() {
  // location of plist file
  if let settingsURL = Bundle.main.path(forResource: "JsonPlist", ofType: "plist") {
    do {
      var settings: MySettings?
      let data = try Data(contentsOf: URL(fileURLWithPath: settingsURL))
      let decoder = PropertyListDecoder()
      settings = try decoder.decode(MySettings.self, from: data)
      print("array  is \(settings?.keyarray1 ?? [""])")//prints ["keyitem1", "keyitem2"]
    } catch {
      print(error)
    }
  }
}

struct MySettings: Codable {
  var keyarray1: [String]?

  init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    keyarray1 = try values.decodeIfPresent([String].self, forKey: .keyarray1)
  }
}

For more see this How to read from a plist with Swift 3 iOS app

Upvotes: 1

rptwsthi
rptwsthi

Reputation: 10172

First of all Check your plist looks like:

enter image description here

Now write following lines where you are accessing your plist

Objective-C:

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

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

enter image description here

Swift:

let dictionary = NSDictionary(contentsOfFile: Bundle.main.pathForResource("Values", ofType: "plist")!);
let array = dictionary?["arrayKey"] as! NSArray
print("dictionary=",  dictionary, "\narray =",  array)

enter image description here

Upvotes: 68

Arnlee Vizcayno
Arnlee Vizcayno

Reputation: 2426

I know this question is too old and I'll just like to add more information for those people encounter this recently.

In my case I created a plist as Array(plist default is Dictionary with key "Root").

enter image description here

then the xml looks like this:

enter image description here

On my view controller I initialize directly the Array instead of initializing the Dictionary then get object for key "Root":

enter image description here

Note: I only wanted to add this info since I only see initializing the Dictionary then get object for keys. Hope it will help you guys.

Upvotes: 5

Ravindhiran
Ravindhiran

Reputation: 5384

Try this

NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"values.plist"];
NSMutableDictionary *dict =[NSMutableDictionary dictionaryWithContentsOfFile:finalPath];
NSArray *arr =[dict valueForKey:@"keyarray1"];
NSLog(@"%@",arr);

Upvotes: -1

Sunil Zalavadiya
Sunil Zalavadiya

Reputation: 1993

Can you try following code?

NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"values" ofType:@"plist"];
NSDictionary * values=[[NSDictionary alloc] initWithContentsOfFile:plistPath];
NSArray *arrayValues=[[NSArray alloc] initWithArray:[values valueForKey:@"keyarray1"]];
NSLog(@"arrayValues = %@",arrayValues);

I got following output in log:-

arrayValues = (
    keyitem1,
    keyitem2
)

Upvotes: 3

zadr
zadr

Reputation: 2515

Where is the plist stored? Is it in the app bundle? If so, you probably want to use [[NSBundle mainBundle] pathForResource:@"values" ofType:@"plist"] to get the path, instead of hardcoding @"values.plist".

After you have the path down correctly, you can then get the array from the dictionary without any problems, with something like [values objectForKey:@"keyarray"].

Final note: there is a difference between objectForKey: and valueForKey:. You're currently using valueForkey: which is part of NSKeyValueCoding, a protocol that NSDictionary happens to conform to. You should use objectForKey: (or syntactic sugar accessors, i.e. dictionary[@"key"]) instead, as they are the proper ways of accessing a value from a dictionary.

Upvotes: 3

Related Questions