2016-08-02 5 views
1

속성 목록에 액세스하는 방법 :다음과 같이 내가 대륙, 국가, 무작위 사실과 속성 목록을 만들었습니다

property list

내가 충분히 쉽게 속성 목록에서 최상위 키에 액세스 할 수 있습니다 :

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

바누아투 배열의 두 번째 요소에 액세스하려는 경우 문제가 발생합니다. 나는 objectForKey가 country 사전을 얻은 다음 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 파일의 데이터를 얻을 수 있습니다. 국가 코드 용 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 = "" 
}