swift - RACObserve 不给出值。 (带有 Swift 的响应式(Reactive) cocoa )

标签 swift reactive-cocoa

dynamic var categories: [Category]?
dynamic var productViewModels: [ProductViewModel]?

var totalCategories = 1

dynamic var currentPage = 0

override init() {
    super.init()

    RACObserve(self, "categories").subscribeNext { [weak self] (x) in
        if let this = self, let categories = x as? [Category] {
            this.totalCategories = categories.count ?? 1 // Why this code doesn't work?
            this.productViewModels = categories.map { ProductViewModel(category: $0.tagName) }
            this.currentPage = 0
        }
    }

    categories = Category.temporaryInitializer()
}

我想如果x有一些值,RACObserve(self, "categories")将使用包含categories的值。但它不包含任何值(value)。 我不知道为什么 x 总是 nil

======已解决问题======

categories = Category.temporaryInitializer() 不应位于 init() 中。

我猜 RACObserveinit() 之后工作正常。

但我还是不知道为什么。

最佳答案

根据Apple Documentation

When you assign a default value to a stored property, or set its initial value within an initializer, the value of that property is set directly, without calling any property observers.

响应式(Reactive)观察者在 KVO 上工作。我想这就是你的观察者没有被调用的原因。

关于swift - RACObserve 不给出值。 (带有 Swift 的响应式(Reactive) cocoa ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31647581/

相关文章:

ios - textField delegate 和 ReactiveCocoa 中使用 textSignal 有什么区别?

ios - 如何使用返回 UIBezierPath 的函数来启动动画?

swift - 隐式展开的可选枚举投诉

ios - 寻找 cocoa 模块的框架

swift - 继承 NSViewController 和 NSImageView (Swift)

ios - rac_signalForSelector fromProtocol,选择器不存在

objective-c - ReactiveCocoa 中的缓存失效

ios - 如何将 UIPanGestureRecognizer 添加到在 CAShapLayer 上绘制的形状 - swift?

ios - UITextField 获得焦点,然后由于在 textFieldShouldReturn 中返回 YES 而立即失去焦点

objective-c - 在有限数量的线程上并行订阅 ReactiveCocoa 信号