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()
中。
我猜 RACObserve
在 init()
之后工作正常。
但我还是不知道为什么。
最佳答案
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/