0

I got the following problem. I got an extension of UIView which contains a view for displaying a value (in this case a battery value of a paired BT device). I need to have this view in several viewcontroller while the value comes from one final class (which receives and handles the device values).

Is there any way to make this UIView "static" so that the DeviceClass changes the Value in the BatteryClass and this is changed in all childs of the BatteryClass? Or is there any other way to realize this better? I just dont want to code for every viewcontroller a new method to update the BatteryView.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Paco89
  • 25
  • 8
  • 1
    Can you add your extension code? Concerning your issue, I think its better to store only your value (in your AppDelegate for example) – Y.Bonafons Nov 13 '17 at 11:25
  • Sure thing, but how does the UIView then know that the value has changed and needs to adopt the its view? – Paco89 Nov 13 '17 at 12:12
  • The simpliest way (not the most beautiful imho) is to use NotificationCenter: https://stackoverflow.com/questions/24049020/nsnotificationcenter-addobserver-in-swift – Y.Bonafons Nov 13 '17 at 12:29

1 Answers1

0

@Y.Bonafons actually has the right answer. The best way for me is here using the NotificationCenter as I have a 1-to-N communication.

Once the battery handler registers a change in the Battery value it posts via the NotificationCenter the new value and all registered obervers handle the changed value in their class. The only thing I haven't figured out yet if it's possible to also transmit values via the NotificationCenter but I doubt that.

here a short example for Swift 4.0:

class Device: UIViewController{
   func batteryValueChanged(){
      NotificationCenter.default.post(name: Notification.Name("ValueChanged"), object: nil)
   }
}

and in the destination class just add in viewDidLoad:

      NotificationCenter.default.addObserver(self, selector: #selector(self.updateValue()), name: Notification.Name("ValueChanged"), object: nil)

while the Notification.Name("ValueChanged") must be consistend and in the selector an @objc function that is called when the value changed.

Paco89
  • 25
  • 8