读取plist 文件,转换成模型

  1. 我是在项目中直接创建的plist文件,用于存储 图片和文字.格式如下:
Snip20170606_14.png

plist 文件格式如下:

Snip20170606_15.png

读取plist文件代码:

/// 读取plist数据
    func readPlist(fileName:String) -> [[String:String]]{ //
        
        let list = Bundle.main.path(forResource: fileName, ofType: "plist")
        let array = NSArray(contentsOfFile: list!)

        return array as! [[String : String]]
    }

model 格式如下:

class LeftViewModel: NSObject {
    /// 图片
    var icon:String?
    /// 名称
    var title:String?
    
    let properties = ["icon","title"]
    
    init(dict:[String:String]) {
        super.init()
        
        setValuesForKeys(dict)
    }
    
    class func dictToModel(list:[[String:String]]) -> [LeftViewModel]{
        var models = [LeftViewModel]()
        for dict in list {
            models.append(LeftViewModel(dict: dict))
        }
        return models
    }
    
    override func setValue(_ value: Any?, forKey key: String) {
        super.setValue(value, forKey: key)
    }
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    override var description: String{
        let dict = dictionaryWithValues(forKeys: properties)
        return "\(dict)"
    }
    
    /// 获取PList中数据
    class func LeftData() -> [[String:String]]{
        let array = Bundle.main.readPlist(fileName: "LeftViewData")
        return array
    }
}

tableView使用如下:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (dataList?.count)!
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell =  LJLeftViewCell.cell(tableView: tableView)
        
        cell.title.text = dataList?[indexPath.row].title
        // 图片
        let icon = dataList?[indexPath.row].icon
        cell.icon.image = UIImage(named: icon!)
        
        return cell
    }


使用如下:

let leftData = LeftViewModel.LeftData()
let model = LeftViewModel.dictToModel(list: leftData)

打印结果:

Snip20170606_18.png
Snip20170606_17.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,999评论 19 139
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,217评论 30 472
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,259评论 4 61
  • 通常,人们都认为思维方式决定说话方式“怎么想怎么说”嘛。日本沟通大师斋藤孝认为说话方式会影响思维方式。那么,就来...
    嘟鼓鼓阅读 149评论 0 2
  • 记得,杨绛先生曾说过:“你的问题主要是读书不多而想得太多!”是啊,很多时候,本不该存在的都被臆想出来。每次读到这句...
    一粒老师阅读 380评论 2 3