Goo是基于MVVM模式进行IOS开发的一个美妙的粘合剂,实现View中元素属性与ViewModel中数据的对接。
Goo具有简单、易懂、灵活并且只在你需要的时候进行使用的特点。
Goo试图解决什么问题
- 解决传统IOS开发过程中,UI和Model双向赋值
- 界面元素比较难于测试的
- 实现以数据为核心驱动UI行为和显示
Goo的实现方案
Goo通过扩展IOS中的UIControl和UIView,利用KVO和KVC的方式实现ViewModel和View的绑定。
#######示例代码
[self.inputTextbindingWithProperty:@"text"withObject:_vmwithDataSource:@"text"withBindingMode:TwoWay];
上述代码意味把self.inputText这个组件的text属性与_vm这个ViewModel的text进行绑定,产生关联。
数据绑定
[self.inputTextbindingWithProperty:@"text"withObject:_vmwithDataSource:@"text"withBindingMode:TwoWay];
其中关于BindingMode代表数据绑定的模式,在Goo中支持TempWay、OneWay、TwoWay等多种模式
- 无论是UI元素属性还是ViewModel属性,只要发生了更改,TwoWay 就会进行彼此更新。
- OneWay 仅当ViewModel属性发生更改时更新UI元素属性。
- TempWay晋档初次绑定时更新UI元素属性
具体实现
来看UIControl+GBindingSupport.m的bindingWithProperty方法通过以下几个步骤完成绑定工作。
- 更新绑定属性
[self.bindingProperty updateBindingProperty:object withDataSource:dataSource withProperty:property withBindingMode:mode]; - 对ViewModel进行增加观察者
[object addObserver:self forKeyPath:dataSource options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil]; - 为自身增加观察者
[self addObserver:self forKeyPath:property options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil]; - 在观察者中完成对赋值操作
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{...}