wes. i
wes. i

Reputation: 628

Firing a function whenever static variable value changed

I'm developing a iPhone apps using swift to communicate with another device via bluetooth. My question is I want to fire a function on another class(change the display value) whenever the variable received new data from CoreBluetooth. Can someone helps!

Upvotes: 0

Views: 80

Answers (3)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

- I will prefer doing the things in Swift way by using didSet

Example:

var value: Int?
{
    didSet
    {
        print("I just got changed")
    }
}

value = 10

- In Swift we use didSet to update the UI as soon as there is a change in the model.

- In the above example as soon as the variable value is set to 10, its didSet is fired.

- Similarly you can use this to handle the Bluetooth value

Upvotes: 2

Omkar Guhilot
Omkar Guhilot

Reputation: 1698

Wei

Implement delegate to perform it

write a protocol

protocol ValueChangedDelegate {
  func valueChanged(nValue:Int)
}

and implement that protocol in the View controller where you want the new value

class YourCustomClass: ValueChangedDelegate 
{
  func valueChanged(nValue:Int) {
    print("value changed")
  }
}

then implement a delegate and set the delegate to self and call the method when value changes, then all the classes that implement the protocol will receive the new value

You can refer this Delegate in Swift-language

Upvotes: 1

Tyko Rouge
Tyko Rouge

Reputation: 51

This can be accomplished one of two ways, either using KVO or the NSNotificationCenter. In this instance it may be best to go with KVO since you're only listening to a single property.

Upvotes: 2

Related Questions