好的,我在Swift中遇到了addObserver函数的问题。 如果我改变对象B的反应值,那怎么可能呢? (没有A知道B但是B有一个变量,引用了A)
例如:
class A {
var willChange: Int = 0
// if something happened -> willChange = 1
}
class B {
let someThing = A()
//Something like this maybe but i don't really want to check, just get a notice
if someThing.willChange != 0 {
}
func whatEver() {
//called if willChange is changed
...
}
}
不仅如果willChange改变了它必须被通知,只要我想要的任何事情发生在A - >证明B. 思考观察者模式,但也许有人可以解释如果可能的话。
答案 0 :(得分:0)
这样的事情:
class A {
weak var observer : AnyObject?
var willChange: Int = 0{
didSet{
if let bObject = observer as? B{
bObject.whatEver()
}
}
}
}
class B {
let someThing = A()
someThing.observer = self
func whatEver() {
//called if willChange is changed
...
}
}