RxSwift 监听对象属性 PersonModel
class PersonModel: NSObject {
// 1、必须用 @objc dynamic 修饰
dynamic var name: String = ""
dynamic var age: Int = 0
}
import ObjectMapper
@objc class JokeModel: NSObject, Mappable {
var sid: String = ""
var text: String = ""
var type: String = ""
var thumbnail: String = ""
var video: String = ""
var passtime: String = ""
required init?(map: Map) {
}
func mapping(map: Map) {
sid <- map["sid"]
text <- map["text"]
type <- map["type"]
thumbnail <- map["thumbnail"]
video <- map["video"]
passtime <- map["passtime"]
}
}
import UIKit
import RxSwift
import RxCocoa
class ViewController: UIViewController {
// RxSwift 的相关方法生命周期 dispose 管理
let disposeBag = DisposeBag()
var age: Int = 0\
// 2、如果监听数组,数组里的对象必须是class,不能是struct
@objc dynamic lazy var jokeModels: [JokeModel] = Array()
override func viewDidLoad() {
super.viewDidLoad()
let person: PersonModel = PersonModel()
// observe('监听属性的类型',‘属性的名称’),监听的属性必须是 @objc dynamic 修饰
person.rx.observe(String.self, "name").subscribe(onNext: { (name) in
print("name did change (String(describing: name ?? "nil"))")
}).disposed(by: self.disposeBag)
// 3、如果监听对象的属性person.name,对象前面也需要加上@objc
@objc let person: PersonModel = PersonModel()
self.rx.observe(String.self, "person.name").subscribe(onNext: { (name) in
print("name did change (String(describing: name ?? "nil"))")
}).disposed(by: self.disposeBag)
// 循环引用的解决方法[weak self]
person.rx.observe(Int.self, "age").subscribe(onNext: {[weak self] (age) in
self?.age = age ?? 0
print("age did change (String(describing: age))")
}).disposed(by: self.disposeBag)
}
}
ReactiveCocoa 监听对象属性
class : NSObject {
// <>里面可以是任意类型,它代表属性的类型。
lazy var name = MutableProperty<String>("SwiftHomeVC")
let racValue = MutableProperty<Int>(1)
}
override func setRAC() {
super.setRAC()
// 监听name变化
name.producer.startWithValues { (value) in
debugPrint("name = \(value)")
}
// 监听racValue变化
racValue.producer.startWithValues { (value) in
debugPrint("racValue = \(value)")
}
racValue.value = 10
name.value = "SwiftHomeVCs2"
}