【问题标题】:iterating through plist file and storing data in array or Dictionary遍历 plist 文件并将数据存储在数组或字典中
【发布时间】:2018-08-17 14:05:06
【问题描述】:

我是快速编程的新手。我正在尝试学习 plist 文件。我有一个 plist 文件,其中包含国家、州和城市的数据。我想遍历 plist 文件的数据。但我不明白如何创建一个数组或字典来存储国家、州和城市的数据。你能帮助我如何操作 plist 文件的以下数据吗?

    {
Country =     (
            {
        CountryName = India;
        State =             (
                            {
                City =                     (
                    Ahmedabad,
                    Vadodara,
                    Surat,
                    Aanand,
                    Bharuch
                );
                StateName = Gujrat;
            },
                            {
                City =                     (
                    Mumbai,
                    Pune,
                    Nagpur,
                    Nasik,
                    Thane
                );
                StateName = Maharastra;
            },
                            {
                City =                     (
                    Kochi,
                    Kanpur,
                    Alleppey,
                    Thrissur,
                    Thiruvananthapuram
                );
                StateName = Kerala;
            }
        );
            },

【问题讨论】:

    标签: ios swift xcode nsarray plist


    【解决方案1】:

    你可以使用对象映射器

    https://github.com/Hearst-DD/ObjectMapper

    在哪里,安装 pod,然后 创建你的类

        class State : Mappable {
    
          var stateName: String?
          var city: [String]?
    
          required init?(map: Map) {}
    
         func mapping(map: Map) {
             stateName <- map["StateName"]
             city <- map["City"]
    
         }
     }
    
     class Country : Mappable {
         var countryName: String?
         var state: [State]?
    
        required init?(map: Map) {}
    
        func mapping(map: Map) {
            countryName <- map["CountryName"]
            state <- map["State"]
    
        }
    
    }
    
    class CountryData: Mappable {
        var countries: [Country]?
    
        required init?(map: Map) {}
    
        func mapping(map: Map) {
            countries <- map["Country"]
    
        }
    }
    

    以变量形式获取您的 plist 内容

     var dictRoot: NSDictionary?
     var countryItems: [String:AnyObject]?
        if let path = Bundle.main.path(forResource: "MyCountryList" , ofType: "plist") {
            dictRoot = NSDictionary(contentsOfFile: path)
        }
    
        if dictRoot != nil
        {
            // Your dictionary contains an array of dictionary
            // Now pull an Array out of it.
            countryItems  = dictRoot as? [String:AnyObject]
            tableView.reloadData()
    
        }
    
    
    let countryData  = CountryData(JSON: countryItems)
    

    现在你可以随心所欲地使用它

    【讨论】:

    • 为什么要使用第三部分库? Swift 4 提供 Codable 和 PropertyListDecoder。
    • 你可以使用编码,但他也没有说明他正在使用 swift 4
    【解决方案2】:

    // swift 3 使用结构。手动解析数据。

    struct ListData {
        var countries : [Country]?
    
        init(dict:[String:AnyObject]) {
            if let countryDict = dict["Country"] as? [[String:AnyObject]] {
                self.countries = parseArray(dictArray: countryDict)
            }
        }
    
        func parseArray(dictArray:[[String:AnyObject]]) -> [Country] {
            var array = [Country]()
            for dict in dictArray {
                let country = Country(dict: dict)
                array.append(country)
            }
            return array
        }
    }
    struct Country  {
        var countryName : String?
        var states : [State]?
    
        init(dict:[String:AnyObject]) {
            countryName = dict["CountryName"] as? String
    
            if let stateDict = dict["State"] as? [[String:AnyObject]] {
                states = parseArray(dictArray: stateDict)
            }
        }
    
        func parseArray(dictArray:[[String:AnyObject]]) -> [State] {
            var array = [State]()
            for dict in dictArray {
                let state = State(dict: dict)
                array.append(state)
            }
            return array
        }
    }
    struct State {
        var stateName : String?
        var cities : [String]?
    
        init(dict:[String:AnyObject]) {
            self.stateName = dict["StateName"] as? String
    
            if let cityDict = dict["City"] as? [AnyObject] {
                cities = parseArray(dictArray: cityDict)
            }
        }
    
        func parseArray(dictArray:[AnyObject]) -> [String] {
            var array = [String]()
            for dict in dictArray {
                array.append(dict as! String)
            }
            return array
        }
    }
    
     var listData : ListData? = nil
    
     if let path = Bundle.main.path(forResource: "Property List" , ofType: "plist") {
                let rootDict = NSDictionary(contentsOfFile: path) as? [String:AnyObject]
                listData = ListData(dict: rootDict!)
        }
    

    // 使用 swift 4 和可编码协议。

    struct ListData : Codable {
        var countries : [Country]?
    
        enum CodingKeys : String, CodingKey {
            case countries =  "Country"
        }
    
    }
    
    struct Country : Codable {
        var countryName : String?
        var states : [State]?
    
        enum CodingKeys : String, CodingKey {
            case countryName =  "CountryName"
            case states = "State"
        }
    
    }
    
    struct State : Codable {
        var stateName : String?
        var cities : [String]?
    
        enum CodingKeys : String, CodingKey {
            case stateName =  "StateName"
            case cities = "City"
        }
    
    }
    
    var listData : ListData? = nil
    if  let url = Bundle.main.url(forResource: "Property List", withExtension: "plist") {
                if let data = try? Data(contentsOf: url) {
                    let decoder = PropertyListDecoder()
                    do {
                        listData = try decoder.decode(ListData.self, from: data)
                    } catch (let err) {
                        print(err.localizedDescription)
                    }
                }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多