Search code examples
iosswiftobserver-patternkey-value-observing

Observer, Action Listener, KVO in iOS Swift


Okay, I have an issue with the addObserver function in Swift. How is that possible, if I change a value of an object A that object B reacts? (Without A knows B but B has a variable with a reference to 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.


Solution

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