I created a class containing an array. I added an observer to this array in the view controller and made some modifications to this array.
The problem is that when I print the change dictionary returned by registerValueForKeyPath (), I can only see changes like NSKeyValueChangeSetting. In other words, the method tells me that the array has changed, provides me with old and new arrays (containing all the elements), but I would like to get information about which specific elements were added or removed.
Here is a sample code.
This is the class whose array will be observed.
private let _observedClass = ObservedClass() class ObservedClass: NSObject { dynamic var animals = [String]() dynamic var cars = [String]() class var sharedInstance: ObservedClass { return _observedClass } }
And this is the code in my view controller.
class ViewController: UIViewController { var observedClass = ObservedClass.sharedInstance required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) observedClass.addObserver(self, forKeyPath: "animals", options: .New | .Old, context: nil) } deinit { observedClass.removeObserver(self, forKeyPath: "animals") } override func viewDidLoad() { super.viewDidLoad() observedClass.animals.insert("monkey", atIndex: 0) observedClass.animals.append("tiger") observedClass.animals.append("lion") observedClass.animals.removeAtIndex(0) } override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { println(change) } }
When I run the above code, I get this result on the console:
[kind: 1, old: ( ), new: ( monkey )] [kind: 1, old: ( monkey ), new: ( monkey, tiger )] [kind: 1, old: ( monkey, tiger ), new: ( monkey, tiger, lion )] [kind: 1, old: ( monkey, tiger, lion ), new: ( tiger, lion )]
In this example, the change dictionary does not show every new element, because it is added to the array using the change view NSKeyValueChangeInsertion?