数据源状态机:1
2
3
4
5
6
7
8import Foundation
enum ProviderState {
case idle
case loading
case submit
case failed(_ message:String)
}
数据源基类:1
2
3
4
5
6
7
8
9
10
11import Foundation
@objcMembers class ProviderObject: NSObject {
var state:ProviderState? {
didSet {
stateMonitor = !stateMonitor
}
}
var noMoreData:Bool = false
dynamic var stateMonitor: Bool = false
}
使用方法:监听数据源的stateMonitor属性,如果有改变,则手动去获取实际数据、state状态等;优点:
- 可以绕开关联性枚举值无法通过observe监听的问题
- 只需要监听一个属性
测试类:1
2
3
4class DemoProvider: ProviderObject {
var dogAges:[Int] = []
var catAges:[Int] = []
}
KVO实现1
2
3
4
5
6
7
8
9
10
11
12var ob: NSKeyValueObservation?
func setupKVO() {
ob = DemoProvider.observe(\.stateMonitor, changeHandler: { (demo, value) in
switch demo.state {
case idle:
//reload data
case loading:
//show loading animation
....
}
}) }