26

我正在尝试读取包含数组的 plist

<?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>

当我尝试读取 valueForKey:@"keyarray1" 时,我得到空值。我试着读成字符串和数组,螺母没用。

我的代码

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

6 回答 6

68

首先检查你的 plist 看起来像:

enter image description here

现在在您访问 plist 的地方写下以下行

目标-C:

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

这是我的工作窗口的完整屏幕截图(带有日志输出):

enter image description here

迅速:

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

于 2013-04-29T04:59:58.877 回答
5

我知道这个问题太老了,我只想为最近遇到这个问题的人添加更多信息。

在我的例子中,我创建了一个 plist 作为数组(plist 默认是带有键“Root”的字典)。

enter image description here

那么xml看起来像这样:

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.

于 2014-11-30T06:04:59.980 回答
3

plist 存储在哪里?它在应用程序包中吗?如果是这样,您可能想使用[[NSBundle mainBundle] pathForResource:@"values" ofType:@"plist"]来获取路径,而不是硬编码@"values.plist"

正确设置路径后,您可以毫无问题地从字典中获取数组,例如 [values objectForKey:@"keyarray"].

objectForKey:最后说明:和之间有区别valueForKey:。您当前使用的是NSDictionary 恰好符合的协议valueForkey:的一部分。NSKeyValueCoding您应该改用objectForKey:(或语法糖访问器,即dictionary[@"key"]),因为它们是从字典中访问值的正确方法。

于 2013-04-28T23:58:33.847 回答
3

您可以尝试以下代码吗?

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

我在日志中得到以下输出:-

arrayValues = (
    keyitem1,
    keyitem2
)
于 2013-04-29T04:14:24.207 回答
1

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

于 2018-03-12T05:09:20.477 回答
-1

试试这个

NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"values.plist"];
NSMutableDictionary *dict =[NSMutableDictionary dictionaryWithContentsOfFile:finalPath];
NSArray *arr =[dict valueForKey:@"keyarray1"];
NSLog(@"%@",arr);
于 2013-04-29T05:09:16.817 回答