简体   繁体   English

如何从 plist iOS 读取数组

[英]How to read Array from plist iOS

I am trying to read plist which contains array我正在尝试读取包含数组的 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>

when i try to read valueForKey:@"keyarray1", I get null value.当我尝试读取 valueForKey:@"keyarray1" 时,我得到空值。 I tried to read as a string and array nut no use.我试图读取一个字符串和数组 nut 没有用。

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:首先检查你的 plist 看起来像:

在此处输入图片说明

Now write following lines where you are accessing your plist现在在您访问 plist 的地方写下以下几行

Objective-C:目标-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").在我的例子中,我创建了一个 plist 作为数组(plist 默认是带有键“Root”的字典)。

在此处输入图片说明

then the xml looks like this:然后 xml 看起来像这样:

在此处输入图片说明

On my view controller I initialize directly the Array instead of initializing the Dictionary then get object for key "Root":在我的视图控制器上,我直接初始化数组而不是初始化字典然后获取键“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? plist 存储在哪里? 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" .如果是这样,您可能希望使用[[NSBundle mainBundle] pathForResource:@"values" ofType:@"plist"]来获取路径,而不是硬编码@"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"] .路径正确后,您就可以从字典中获取数组而不会出现任何问题,例如[values objectForKey:@"keyarray"]

Final note: there is a difference between objectForKey: and valueForKey: .最后一点: objectForKey:valueForKey:之间存在差异。 You're currently using valueForkey: which is part of NSKeyValueCoding , a protocol that NSDictionary happens to conform to.您目前正在使用valueForkey:它是NSKeyValueCoding一部分,NSDictionary 恰好符合该协议。 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.您应该使用objectForKey: (或语法糖访问器,即dictionary[@"key"] ),因为它们是从字典访问值的正确方法。

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斯威夫特 4

As in Swift 4 you can use codable & PropertyListDecoder与 Swift 4 一样,您可以使用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有关更多信息,请参阅如何使用 Swift 3 iOS 应用程序读取 plist

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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