房地产观察家的行为让我在以下情况下感到惊讶。我知道观察者不会递归地调用自己,但这种行为似乎会转移到同一类的不同实例,甚至是不同子类的实例。
据我所知,属性观察器在任何时候设置属性时都会运行,即使值没有更改,初始化时除外。这条规则的例外到底是什么?房地产观察家到底什么时候会被忽视,如下所示?

var observersCalled = 0

class ClassOne {
    var relatedOne: ClassOne?
    var relatedTwo: ClassTwo?
    var property: String = "Initial" {
        didSet {
            observersCalled += 1
            relatedOne?.property = property
            relatedTwo?.property = property
        }
    }
}

class ClassTwo {
    var property: String = "Initial" {
        didSet {
            observersCalled += 1
        }
    }
}

class Subclass: ClassOne {
    override var property: String {
        didSet {
            observersCalled += 1
        }
    }
}

let thing = ClassOne()
thing.relatedOne = ClassOne()
thing.property = "New Value"
print(observersCalled) //1 (really?)

observersCalled = 0
thing.relatedOne = nil
thing.relatedTwo = ClassTwo()
thing.property = "Another Value"
print(observersCalled) //2 (makes sense)

observersCalled = 0
thing.relatedOne = Subclass()
thing.relatedTwo = nil
thing.property = "Yet Another Value"
print(observersCalled) //1 (really!?)

最佳答案

没有例外。我问的行为是个错误。我已经为那些跟踪它进展的人提交了a bug report

关于swift - 属性(property)观察员什么时候应该运行?有什么异常(exception)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34523491/

10-15 15:27