物业观察员什么时候开始运作?有什么例外?

时间:2015-12-30 05:32:09

标签: swift properties observers

在下列情况下,财产观察员的行为让我感到惊讶。我理解观察者不会递归地调用自己,但是这种行为似乎会延续到同一个类的不同实例,甚至延伸到不同子类的实例。

据我了解,属性观察者在设置属性时运行,即使值没有改变,初始化除外。这条规则的例外究竟是什么?财产观察员究竟会被忽视,如下所示?

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!?)

1 个答案:

答案 0 :(得分:0)

没有例外。我问过的行为是一个错误。我已为跟踪其进度的人提交了a bug report