2016-08-02 62 views
1

我已經創建,如下圖所示與大洲,國家和隨機事實屬性列表:如何訪問一個屬性列表

property list

我可以訪問屬性列表中很容易夠頂級鍵:

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

但是,如果我想訪問瓦努阿圖數組中的第二個元素,事情就會崩潰。我會認爲objectForKey會得到國家字典,然後再次使用objectForKey來獲取國家數組。但到目前爲止,這還沒有奏效。在所有...

回答

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 
       } 
      } 
     } 
2
if let path = NSBundle.mainBundle().pathForResource("Property List", ofType: "plist") { 
     dict = NSDictionary(contentsOfFile: path) 
     if let vanuatu = dict.objectForKey("australia") as? [String:AnyObject]{ 
      if let vanuatuArray = vanuatu["vanuatu"] as? [String]{ 
       print(vanuatuArray[1]) 
      } 
     } 

    } 
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 = "" 
}