简体   繁体   English

观察者,动作监听者,iOS Swift中的KVO

[英]Observer, Action Listener, KVO in iOS Swift

Okay, I have an issue with the addObserver function in Swift. 好的,我在Swift中的addObserver函数有问题。 How is that possible, if I change a value of an object A that object B reacts? 如果我更改对象B的值,对象B会如何反应? (Without A knows B but B has a variable with a reference to A) (没有A知道B,但是B具有引用A的变量)

for example here: 例如这里:

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
  ...
  }
}

Not only if willChange changed it has to be notificated, just if anything i want happened in A -> notificate B. Thinking of Observer Pattern, but maybe can someone explain if possible with this. 不仅将willChange更改了,还必须通知我,即使我想要在A->通知B中发生任何事情。考虑观察者模式,但也许有人可以对此进行解释。

Something like this: 像这样:

 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 ... } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM