如何在Swift中不使用NSDictionary读取Plist?

时间:2016-11-05 10:01:30

标签: ios swift dictionary swift3 nsdictionary

我已经在Swift 2中使用过这种方法

var myDict: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") {
myDict = NSDictionary(contentsOfFile: path)
}

但是不知道如何在不使用的情况下阅读Swift3中的plist NSDictionary(contentsOfFile:path)

2 个答案:

答案 0 :(得分:23)

原生的Swift方式是使用PropertyListSerialization

if let url = Bundle.main.url(forResource:"Config", withExtension: "plist") {
   do {
     let data = try Data(contentsOf:url)
     let swiftDictionary = try PropertyListSerialization.propertyList(from: data, format: nil) as! [String:Any]
      // do something with the dictionary
   } catch {
      print(error)
   }
}

您还可以使用NSDictionary(contentsOf:类型广告:

if let url = Bundle.main.url(forResource:"Config", withExtension: "plist"),
   let myDict = NSDictionary(contentsOf: url) as? [String:Any] {
   print(myDict)
}

但你明确地写了:而不使用NSDictionary(contentsOf ...

基本上不使用NSDictionary而不在Swift中进行投射,你丢弃了重要的类型信息。

答案 1 :(得分:3)

PropertyListDecoder 可用于将plist文件直接解码为对象。

1:示例Plist文件(sample.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>valua for key1</string>
    <key> key2</key>
    <string>valua for key1</string>
    <key>CustomClass1</key>
    <dict>
        <key>customClass1_key</key>
        <string>customClass1_value</string>
    </dict>
    <key>CustomClass2</key>
    <dict>
        <key>customClass2_kek</key>
        <string>customClasse_value</string>
    </dict>
</dict>
</plist>

2:plist的核心搜索模型

struct PlistConfiguration:Codable {
    var key1:String?
    var customClass1Obj: CustomClass1?
    var customClass2Obj: CustomClass2?
    
    private enum CodingKeys : String, CodingKey {
              case key1 = "key1"
              case customClass1Obj = "CustomClass1"
              case customClass2Obj = "CustomClass2"
    }
    
}

2.1:嵌套模型

struct CustomClass1:Codable {
    var customClass1_key:String?
    private enum CodingKeys : String, CodingKey {
              case customClass1_key = "customClass1_key"
    }
    
}

2.2:嵌套模型

struct CustomClass2:Codable {
    var customClass2_key:String?
    private enum CodingKeys : String, CodingKey {
              case customClass2_key = "customClass2_key"
    }
    
}

3:从主应用程序包中读取Plist

func parseConfig() -> PlistConfiguration {
        let url = Bundle.main.url(forResource: "sample", withExtension: "plist")!
        let data = try! Data(contentsOf: url)
        let decoder = PropertyListDecoder()
        return try! decoder.decode(PlistConfiguration.self, from: data)
    }