美文网首页
swift -观察数组

swift -观察数组

作者: _锋 | 来源:发表于2017-08-23 09:03 被阅读0次

    classKnowViewModel:NSObject{

    //被观察的属性必须用dynamic修饰

    dynamicvardataSourceForKnowViewModel : [KnowModel]! = []//数组

    }

    //懒加载创建数组

    /* 1.

    lazy var dataArray : NSArray = {

    return NSArray()

    }()

    */

    //2.

    lazyvardataSource :Array = {

    vartmpArray :Array! = []//初始化

    returntmpArray

    }()

    classKnowHuViewController:UIViewController,UITableViewDataSource,UITableViewDelegate{

    //3.MARK:定义属性viewModel一定要var,并没有初始化

    varknowViewModle :KnowViewModel!

    overridefuncviewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view.

    self.title="知乎MVVM"

    //初始化控件

    configurationKnowHuView()

    //3.初始化knowViewModle

    knowViewModle=KnowViewModel.init()

    //添加观察者,写在初始化后面

    knowViewModle.addObserver(self, forKeyPath:"dataSourceForKnowViewModel", options: .New, context:nil)

    knowViewModle.getDailyThemesDataWithThemeID(10)

    }

    //MARK:实现观察者方法

    overridefuncobserveValueForKeyPath(keyPath:String?, ofObject object:AnyObject?, change: [String:AnyObject]?, context:UnsafeMutablePointer) {

    ifkeyPath =="dataSourceForKnowViewModel"{

    //将viewModle里面的数据赋给dataSource

    self.dataSource=knowViewModle.dataSourceForKnowViewModel

    self.tableView.reloadData()

    }

    }

    //MARK:移除观察者

    deinit{

    knowViewModle.removeObserver(self, forKeyPath:"dataSourceForKnowViewModel")

    }

    }

    相关文章

      网友评论

          本文标题:swift -观察数组

          本文链接:https://www.haomeiwen.com/subject/jhtddxtx.html