如何使用 ReactiveCocoa 观察 属性 在 Swift 中的变化

How to observe property changed in Swift with ReactiveCocoa

我正在用新的 ReactiveCocoa + ReactiveSwift 编写 Swift。我正在尝试使用新的 ReactiveCocoa 框架执行以下操作(在 ReactiveCocoa 2.5 中):

[[RACObserve(user, username) skip:1] subscribeNext:^(NSString *newUserName) {
    // perform actions...
}];

经过一些研究,我仍然不知道该怎么做。请帮忙!非常感谢!

您的代码段通过 KVO 工作,这在 Swift 中的最新 RAC/RAS 仍然可行,但不再是 推荐的方式。

使用属性

推荐的方式是使用Property,它有一个值,可以被观察到。

这是一个例子:

struct User {
  let username: MutableProperty<String>
  init(name: String) {
    username = MutableProperty(name)
  }
}

let user = User(name: "Jack")

// Observe the name, will fire once immediately with the current name
user.username.producer.startWithValues { print("User's name is \([=10=])")}
// Observe only changes to the value, will not fire with the current name
user.username.signal.observeValues { print("User's new name is \([=10=])")}

user.username.value = "Joe"

这将打印

User's name is Jack

User's name is Joe

User's new name is Joe

使用 KVO

如果出于某种原因您仍然需要使用 KVO,请按以下步骤操作。请记住,KVO 仅适用于 NSObject 的显式子 class,如果 class 写在 Swift 中,则 属性 需要用 @objc dynamic!

注释
class NSUser: NSObject {
  @objc dynamic var username: String
  init(name: String) {
    username = name
    super.init()
  }
}

let nsUser = NSUser(name: "Jack")

// KVO the name, will fire once immediately with the current name
nsUser.reactive.producer(forKeyPath: "username").startWithValues { print("User's name is \([=11=])")}
// KVO only changes to the value, will not fire with the current name
nsUser.reactive.signal(forKeyPath: "username").observeValues { print("User's new name is \([=11=])")}

nsUser.username = "Joe"

这将打印

User's name is Optional(Jack)

User's new name is Optional(Joe)

User's name is Optional(Joe)