4

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

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

经过一些研究,我仍然无法弄清楚如何做到这一点。请帮忙!非常感谢!

4

1 回答 1

18

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

使用属性

推荐的方法是使用Propertywhich 持有一个值并且可以被观察到。

这是一个例子:

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 \($0)")}
// Observe only changes to the value, will not fire with the current name
user.username.signal.observeValues { print("User's new name is \($0)")}

user.username.value = "Joe"

这将打印

用户名是杰克

用户名为乔

用户的新名字是 Joe

使用 KVO

如果由于某种原因您仍然需要使用 KVO,那么您可以这样做。请记住,KVO 仅适用于 的显式子类NSObject,如果该类是用 Swift 编写的,则该属性需要使用@objc and 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 \($0)")}
// 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 \($0)")}

nsUser.username = "Joe"

这将打印

用户名是可选的(Jack)

用户的新名称是 Optional(Joe)

用户名是可选的(Joe)

于 2017-12-01T09:08:50.693 回答