swiftsetkey-value-observing

Swift 3 KVO to observe change in NSMutableSet (add, remove, modify item)


I'm develop an app which has an set of unique string. I have a function to add, remove, modify item in the NSMutableSet. I want to use KVO (key value observer) to observe whenever the set has change (add, remove, modify item).

Here's my code:

dynamic var barCodeSet = NSMutableSet()

in viewDidload I add observe:

    override func viewDidLoad() {
        super.viewDidLoad()
        
        addObserver(self, forKeyPath: #keyPath(barCodeSet), options: [.old,.new,.initial], context: nil)
        
    }

And this is my observe function:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == #keyPath(barCodeSet) {
            print(barCodeSet.count)
            for barcode in barCodeSet {
                print(barcode)
            }
        }
    }

I don't know why the KVO is not working. How can I modify the code so that we can get notify when set items change?


Solution

  • Assuming you do not need to use NSMutableSet, you could use a didSet clause in the variable declaration. try the following in a playground:

    import UIKit
    
    class myClass {
    
        init() {
    
        }
    
        dynamic var barCodeSet: Set<String> = Set<String>() {
            didSet {
                print(barCodeSet.count)
                for barcode in barCodeSet {
                    print(barcode)
                }
            }
        }
    }
    
    let thisClass = myClass()
    
    thisClass.barCodeSet = ["Apples", "Bananas", "Oranges"]
    thisClass.barCodeSet.insert("Grapes")
    

    Whenever you set the value of barCodeSet, its count and contents are printed to the console.