Lê Khánh Vinh Lê Khánh Vinh - 1 month ago 20
Swift Question

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

Hi 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 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)
}
}
}


Don't know why the KVO is not working. Any one know how to modify the code so that we can get notify when set items change? Thanks

Answer

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.