将.plist数据读入Swift中的字典

时间:2015-11-30 18:15:35

标签: ios swift plist

我在将plist文件中的XML数据读入字典时遇到问题。问题包括plist没有被识别为捆绑包的一部分,尽管有正确的选项将它添加到导入时检查的项目。

我正在寻找一种简单的方法来在程序启动时读取数据,然后通过访问阵列的方法轻松获取数据。数据不需要重写或更改,因此只需一次传输即可使程序正常运行。

以下是.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">
<array>
    <dict>
        <key>Name</key>
        <string>19” HD Monitor</string>
        <key>Price</key>
        <integer>11999</integer>
        <key>ProdId</key>
        <integer>123</integer>
    </dict>
    <dict>
        <key>Name</key>
        <string>4GB RAM Module</string>
        <key>Price</key>
        <integer>2995</integer>
        <key>ProdId</key>
        <integer>456</integer>
    </dict>
    <dict>
        <key>Name</key>
        <string>Samsung 256GB SSD</string>
        <key>Price</key>
        <integer>11250</integer>
        <key>ProdId</key>
        <integer>789</integer>
    </dict>
</array>
</plist>

数据包括产品名称(String),便士价格或美分(Int)和唯一产品ID(Int)。这些的关键名称是&#39; Name&#39;,&#39; Price&#39;和&#39; ProdID&#39;分别

这是我用来读取数据的代码。我使用简单的命令行程序以简单的形式隔离此操作,并测试数据是否有已经从字典中存储和检索。数据操作将在类中提供:

//
//  Datadump.swift
//  PListTester
//
//  Created by Kwangle on 30/11/2015.
//  Copyright (c) 2015 KwangCo All rights reserved.
//

import Foundation


class Datadump {


    //declare container array
    var dictArray: Array<Dictionary<String,AnyObject>>

    //reads data when class is constructed
    init () {

        let bundle = NSBundle(forClass: Datadump.self)
        //gets file location of 'Products.plist' from bundle
        let fileLocation = bundle.pathForResource("Hardware", ofType: "plist")

        //creates NSArray from contents of 'Hardware.plist'
        let productArray = NSArray(contentsOfFile: fileLocation!)
        //creates dictionary array from NSArray via force conversion
        dictArray = productArray as! Array<Dictionary<String,AnyObject>>

        for (var i = 0; i < dictArray.count; i++){
            dictArray.append(productArray!.objectAtIndex(i) as! Dictionary<String, AnyObject>)
        }
    }

//reads price value of matching ProdID  
        func priceFromID(pId: Int) -> Int{
            var price = 0
            //iterate through array until relevant product is found
            for dict in dictArray{
                //reads 'ProdId' key and compares it to pId function argument
                if dict["ProdId"] as! Int == pId{
                    //if product ID is found price is set to its value
                    price = dict["Price"] as! Int
                    break
                }
            }

        return price;

    }

}//end class

Main方法只是创建一个DataDump类的实例,并使用与ProdId匹配的值运行priceFromID方法:

//
//  main.swift
//  PListTester
//
//  Created by Kwangle on 29/11/2015.
//  Copyright (c) 2015 KwangCo All rights reserved.
//

import Foundation

//creates instance of Datadump class
var myData = Datadump ()

//queries data
print (myData.priceFromID(123) )

我得到的错误是:

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)

这与行:

有关
let productArray = NSArray(contentsOfFile: fileLocation!)

我也收到了错误代码:

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

对此的任何帮助将不胜感激!

非常感谢, 千瓦

1 个答案:

答案 0 :(得分:0)

您不希望将内容加载到数组中。你想要一本字典。

看这里;

How to read data structure from .plist file into NSArray