简体   繁体   中英

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

First of all Check your plist looks like:

在此处输入图片说明

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:

在此处输入图片说明

Swift:

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

在此处输入图片说明

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").

在此处输入图片说明

then the xml looks like this:

在此处输入图片说明

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

在此处输入图片说明

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.

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, ie dictionary[@"key"] ) instead, as they are the proper ways of accessing a value from a dictionary.

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
)

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM