Swift缩水版MJExtension - Reflect的基本使用

github:https://github.com/CharlinFeng/Reflect

直接拖拽Reflect文件夹到您的项目中即可,无任何第三方依赖!
文件夹结构说明:
.Coding 归档相关
.Reflect 反射核心包
.Dict2Model 字典转模型
.Model2Dict 模型转字典

这里使用plist作为数据源, plist存储的是一个数组, 数组中存储的是字典

plist的结构如下:

将plist数组中的每一个字典转换为模型, 代码如下:

RPTableViewController.swift:

import UIKit

class RPTableViewController: UITableViewController {
    
    var datas:[RPCityGroupModel] = Array()

    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        let path = NSBundle.mainBundle().pathForResource("cityGroups", ofType: ".plist")
        let arr = NSArray(contentsOfFile: path!)
        for dict in arr! {
            self.datas.append(RPCityGroupModel.parse(dict: dict as! NSDictionary))
        }
        
        self.navigationItem.leftBarButtonItem = editButtonItem()
    }

    // MARK: - Table view data source
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return self.datas.count
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return self.datas[section].cities.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)

        cell.textLabel!.text = self.datas[indexPath.section].cities[indexPath.row]

        return cell
    }
    
    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
    {
        return self.datas[section].title
    }
    
    override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]?
    {
        var indexTitles: [String] = Array()
        for model in self.datas {
            indexTitles.append(model.title)
        }
        return indexTitles
    }
    
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
    {
        if editingStyle == .Delete {
            self.datas[indexPath.section].cities.removeAtIndex(indexPath.row)
            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        }
    }
}

RPCityGroupModel.swift:

这里要注意的是, 模型是继承于Reflect这个类的

import UIKit

class RPCityGroupModel: Reflect 
{
    var cities: [String] = []
    var title: String = ""
}

gif:

posted @ 2016-02-13 19:21  Rinpe  阅读(537)  评论(0编辑  收藏  举报