【问题标题】:When should property observers run? What are the exceptions?什么时候应该运行属性观察器?有哪些例外?
【发布时间】:2015-12-30 05:32:09
【问题描述】:

在以下情况下,财产观察者的行为让我感到惊讶。我知道观察者不会递归调用自己,但这种行为似乎会延续到同一类的不同实例,甚至会延续到不同子类的实例。

据我了解,属性观察者会在任何时候设置属性时运行,即使值没有改变,初始化除外。这条规则到底有哪些例外?如下所示,究竟什么时候会忽略属性观察者?

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

【问题讨论】:

  • 看起来像一个错误。我认为您可以通过删除 ClassTwo 和 Subclass 以及相关演示来改进测试用例。另外,我会在 ClassOne 上添加一个 bool 属性(默认为 false),并在 didSet 观察者中将其设置为 true。然后 print("thing run didSet: (thing.didSetExecuted) [expected true]") 和 print("thing.related run didSet: (thing.relatedOne?.didSetExecuted) [expected true]")。然后将错误提交到bugs.swift.org

标签: swift properties observers


【解决方案1】:

没有例外。我问的行为是一个错误。我已提交a bug report 供那些跟踪其进度的人使用。

【讨论】:

    猜你喜欢
    • 2012-06-10
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 2020-12-22
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    相关资源
    最近更新 更多