gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:31:09 25 4
gpt4 key购买 nike

我正在使用新的 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 \($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"

将打印

User's name is Jack

User's name is Joe

User's new name is Joe

使用 KVO

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

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"

将打印

User's name is Optional(Jack)

User's new name is Optional(Joe)

User's name is Optional(Joe)

关于swift - 如何使用 ReactiveCocoa 在 Swift 中观察属性的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47584650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com