0

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.

Lirf
  • 111
  • 12

1 Answers1

0

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
  ...
  }
}
Peter Peng
  • 1,910
  • 1
  • 27
  • 37
  • Does not work.. Says only that whatEver not exists in class B, but it does. – Lirf Sep 01 '16 at 01:13
  • Sorry, it works very good! is the performance good for things like this? – Lirf Sep 01 '16 at 01:25
  • Good to know. There shouldn't be any impact on the performance. For your use case, just remember that "observer" in class A needs to be weak. – Peter Peng Sep 01 '16 at 01:47