如何从plist iOS中读取数组

时间:2013-04-28 23:25:58

标签: ios objective-c swift

我正在尝试读取包含数组的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"]];

6 个答案:

答案 0 :(得分:66)

首先检查你的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

答案 1 :(得分:5)

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

在我的情况下,我创建了一个plist作为Array(plist默认为Dictionary,键为“Root”)。

enter image description here

然后xml看起来像这样:

enter image description here

在我的视图控制器上,我直接初始化数组而不是初始化Dictionary然后获取关键字“Root”的对象:

enter image description here

注意:我只想添加此信息,因为我只看到初始化Dictionary然后获取键的对象。希望它会帮助你们。

答案 2 :(得分:3)

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

正确地关闭路径后,您可以从字典中获取数组而不会出现任何问题,例如[values objectForKey:@"keyarray"]

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

答案 3 :(得分: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
)

答案 4 :(得分:1)

Swift 4

与Swift 4一样,您可以使用可编码&amp; 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)

    }
}

有关详情,请参阅此How to read from a plist with Swift 3 iOS app

答案 5 :(得分:-1)

试试这个

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