Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a method when a variable value changes in Swift

I need to execute a function when a variable value changes.

I have a singleton class containing a shared variable called labelChange. Values of this variable are taken from another class called Model. I have two VC classes, one of them has a button and a label and the second only a button.

When the button in the first VC class is pressed I am updating the label with this func:

func updateLabel(){
    self.label.text = SharingManager.sharedInstance.labelChange
}

But I want to call the same method whenever the value of the labelChange is changed. So in button click I will only update the labelChange value and when this thing happen I want to update the label with the new value of the labelChange. Also in the second VC I am able to update the labelChange value but I am not able to update the label when this value is changed.

Maybe properties are the solution but can anyone show me how to do so.

Edited second time:

Singleton Class:

class SharingManager {
    func updateLabel() {
        println(labelChange)
        ViewController().label.text = SharingManager.sharedInstance.labelChange     
    }
    var labelChange: String = Model().callElements() {
        willSet {
            updateLabel()
        }
    }
    static let sharedInstance = SharingManager()
}

First VC:

class ViewController: UIViewController {
    @IBOutlet weak var label: UILabel!
    @IBAction func Button(sender: UIButton) {    
       SViewController().updateMessageAndDismiss()
    }
}

Second VC:

func updateMessageAndDismiss() {
        SharingManager.sharedInstance.labelChange = modelFromS.callElements()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
@IBAction func b2(sender: UIButton) { 
        updateMessageAndDismiss()
}

I made some improvements but I need to reference a label from the first VC class in singleton. Therefore I will update that label of VC in singleton.

When I print the value of labelChange the value is being updated and everything is fine. But when I try to update that value on label from singleton I receive an error:

unexpectedly found nil while unwrapping an Optional value

and the error is pointing in 4th line of singleton class.

like image 796
Ilir V. Gruda Avatar asked Jun 03 '15 15:06

Ilir V. Gruda


5 Answers

You can simply use a property observer for the variable, labelChange, and call the function that you want to call inside didSet (or willSet if you want to call it before it has been set):

class SharingManager {
    var labelChange: String = Model().callElements() {
        didSet {
            updateLabel()
        }
    }
    static let sharedInstance = SharingManager()
}

This is explained in Property Observers.

I'm not sure why this didn't work when you tried it, but if you are having trouble because the function you are trying to call (updateLabel) is in a different class, you could add a variable in the SharingManager class to store the function to call when didSet has been called, which you would set to updateLabel in this case.


Edited:

So if you want to edit a label from the ViewController, you would want to have that updateLabel() function in the ViewController class to update the label, but store that function in the singleton class so it can know which function to call:

class SharingManager {
    static let sharedInstance = SharingManager()
    var updateLabel: (() -> Void)?
    var labelChange: String = Model().callElements() {
        didSet {
            updateLabel?()
        }
    }
}

and then set it in whichever class that you have the function that you want to be called, like (assuming updateLabel is the function that you want to call):

SharingManager.sharedInstance.updateLabel = updateLabel

Of course, you will want to make sure that the view controller that is responsible for that function still exists, so the singleton class can call the function.

If you need to call different functions depending on which view controller is visible, you might want to consider Key-Value Observing to get notifications whenever the value for certain variables change.

Also, you never want to initialize a view controller like that and then immediately set the IBOutlets of the view controller, since IBOutlets don't get initialized until the its view actually get loaded. You need to use an existing view controller object in some way.

Hope this helps.

like image 79
Dennis Avatar answered Oct 05 '22 15:10

Dennis


In Swift 4 you can use Key-Value Observation.

label.observe(\.text, changeHandler: { (label, change) in
    // text has changed
})

This is basically it, but there is a little catch. "observe" returns an NSKeyValueObservation object that you need to hold! - when it is deallocated, you’ll receive no more notifications. To avoid that we can assign it to a property which will be retained.

var observer:NSKeyValueObservation?
// then assign the return value of "observe" to it
observer = label.observe(\.text, changeHandler: { (label, change) in
    // text has changed,
})

You can also observe if the the value has changed or has been set for the first time

observer = label.observe(\.text, changeHandler: { (label, change) in
    // just check for the old value in "change" is not Nil
    if let oldValue = change.oldValue {
        print("\(label.text) has changed from \(oldValue) to \(label.text)")
    } else {
        print("\(label.text) is now set")
    }

})

For More Information please consult Apples documentation here

like image 34
Andy Avatar answered Oct 05 '22 15:10

Andy


Apple provide these property declaration type :-

1. Computed Properties:-

In addition to stored properties, classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

var otherBool:Bool = false
public var enable:Bool {
    get{
        print("i can do editional work when setter set value  ")
        return self.enable
    }
    set(newValue){
        print("i can do editional work when setter set value  ")
        self.otherBool = newValue
    }
}

2. Read-Only Computed Properties:-

A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.

var volume: Double {
    return volume
}

3. Property Observers:-

You have the option to define either or both of these observers on a property:

willSet is called just before the value is stored.
didSet is called immediately after the new value is stored.

public  var totalSteps: Int = 0 {
    willSet(newTotalSteps) {
        print("About to set totalSteps to \(newTotalSteps)")
    }
    didSet {
        if totalSteps > oldValue  {
            print("Added \(totalSteps - oldValue) steps")
        }
    }
}

NOTE:- For More Information go on professional link https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

like image 31
Abhimanyu Rathore Avatar answered Oct 05 '22 14:10

Abhimanyu Rathore


There is another way of doing so, by using RxSwift:

  1. Add RxSwift and RxCocoa pods into your project

  2. Modify your SharingManager:

    import RxSwift
    
    class SharingManager {
        static let sharedInstance = SharingManager()
    
        private let _labelUpdate = PublishSubject<String>()
        let onUpdateLabel: Observable<String>? // any object can subscribe to text change using this observable
    
        // call this method whenever you need to change text
        func triggerLabelUpdate(newValue: String) {
            _labelUpdate.onNext(newValue)
        }
    
        init() {
            onUpdateLabel = _labelUpdate.shareReplay(1)
        }
    }
    
  3. In your ViewController you can subscribe to value update in two ways:

    a. subscribe to updates, and change label text manually

    // add this ivar somewhere in ViewController
    let disposeBag = DisposeBag()
    
    // put this somewhere in viewDidLoad
    SharingManager.sharedInstance.onUpdateLabel?
        .observeOn(MainScheduler.instance) // make sure we're on main thread
        .subscribeNext { [weak self] newValue in
            // do whatever you need with this string here, like:
            // self?.myLabel.text = newValue
        }
        .addDisposableTo(disposeBag) // for resource management
    

    b. bind updates directly to UILabel

    // add this ivar somewhere in ViewController
    let disposeBag = DisposeBag()
    
    // put this somewhere in viewDidLoad
    SharingManager.sharedInstance.onUpdateLabel?
        .distinctUntilChanged() // only if value has been changed since previous value
        .observeOn(MainScheduler.instance) // do in main thread
        .bindTo(myLabel.rx_text) // will setText: for that label when value changed
        .addDisposableTo(disposeBag) // for resource management
    

And don't forget to import RxCocoa in ViewController.

For triggering event just call

SharingManager.sharedInstance.triggerLabelUpdate("whatever string here")

HERE you can find example project. Just do pod update and run workspace file.

like image 34
Valerii Lider Avatar answered Oct 05 '22 15:10

Valerii Lider


var item = "initial value" {
    didSet { //called when item changes
        print("changed")
    }
    willSet {
        print("about to change")
    }
}
item = "p"
like image 28
msk_sureshkumar Avatar answered Oct 05 '22 16:10

msk_sureshkumar