如何访问属性列表

时间:2016-08-02 05:41:02

标签: ios swift property-list

我创建了一个包含大陆,国家和随机事实的属性列表,如下所示:

property list

我可以轻松地从属性列表中访问顶级键:

if let path = NSBundle.mainBundle().pathForResource("countryData", ofType: "plist") {
            dict = NSDictionary(contentsOfFile: path)
        }
countries += dict!.allKeys as! [String]

但是,如果我想访问瓦努阿图阵列中的第二个元素,事情就会崩溃。我认为objectForKey将获取国家字典,然后再次使用objectForKey来获取国家/地区数组。但到目前为止,这还没有奏效。完全......

3 个答案:

答案 0 :(得分:3)

if let path = NSBundle.mainBundle().pathForResource("countryData", ofType: "plist") {
            dict = NSDictionary(contentsOfFile: path)

            if let australia = dict["australia"] as? [String:AnyObject]{
                // access the second element's property here
            if let vanuatu = australia["vanuatu"] as? [String]{
                // Access the vanuatu here
                } 
            }
        }

答案 1 :(得分:2)

SELECT dimension,
       CASE when(impressions!=0) THEN clicks/impressions*100
           ELSE NULL
       END ctr,
       CASE when(impressions!=0) THEN gross_rev/impressions*1000
           ELSE NULL
       END cpm,
       CASE when(clicks!=0) THEN gross_rev/clicks
           ELSE NULL
       END cpc,
       CASE when(actions!=0) THEN gross_rev/actions
           ELSE NULL
       END AS cpa,
       CASE when(post_click!=0) THEN gross_rev/post_click
           ELSE NULL
       END AS pc_cpa

答案 2 :(得分:1)

您可以从plist文件中获取数据。 我为countryCodes创建了一个plist文件。

func fetchCounrtyCodes() -> [CountryCodes]{
let name = "name"
let dial_code = "dial_code"
let code = "code"

var countryArray = [CountryCodes]()

guard let filePath = NSBundle.mainBundle().pathForResource("CountryList", ofType: "json") else {
    print("File doesnot exist")
    return []
}
guard let jsonData = NSData(contentsOfFile: filePath) else  {
    print("error parsing data from file")
    return []
}
do {
    guard let jsonArray = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) as? [[String:String]] else {
        print("json doesnot confirm to expected format")
        return []
    }
    countryArray = jsonArray.map({ (object) -> CountryCodes in
        return CountryCodes(name: object[name]!, dial_code:object[dial_code]!, code: object[code]!)
    })
}
catch {
    print("error\(error)")
}
return countryArray
}

struct CountryCodes{
var name = ""
var dial_code = ""
var code = ""
}