Pages

Learning Key Value Observing with an example

Key value observing is a feature in Swift that depends on dynamically dispatched methods. You might ask what thats means, well dynamically dispatched methods are those instance methods of an object which are run by querying the related object. For further explanation I recommend that you refer to my post "Key Value Observing In Swift". Let us learn it with an example in which we will have two text fields first one is for entering name, second one if for entering age && a button in storyboard. Now create two outlets for the two textfields && an action function fro button below shown picture is showing this arrangement:

Here in this above shown picture you also can see that there are two global properties are also defined name && age of String && Int type you also mimic this I will explain this soon enough.
Now in your project a class file which is expanding "NSObject" class, name it as you want in this example my class name is "toBeObserved.swift" as you can see in the figure it's object is created. Do you know why we did this means created a class which is extending NSObject class, because when you implement Key Value Observing feature the the property that you want to observe should be of class which is extanding NSObject class. The property should marked with keyword "dynamic". So open you newly created class && write the below written code in it.

import UIKit
class toBeObserved: NSObject {    
    dynamic var name: String = ""
    dynamic var age: Int = 0    
    func updatingValues() {        
        name = name1
        age = age1
    }
}
Here all this code is doing is initializing two properties which you will be observing in ViewController.Swift class. Notice that the properties are marked with "dynamic" keyword. After all KVO works with Dynamic dispatching, you know. And in update function we are updating these two name && age properties by assigning the values of name1 && age1 properties which are globally declared as you can see in very first figure. Now lets move to the ViewController.Swift file after all that is the main feast in this particular example.
In ViewController.Swift file lets add the observer for these two properties "name && age" of toBeObserved.swift class. Now update the "done" function of ViewController.Swift class with below written code...

    @IBAction func done(sender: AnyObject) {  
        name1 = nameField.text
        age1 = (ageField.text).toInt()!
        toBeObservedClass = toBeObserved()        
        toBeObservedClass?.addObserver(self, forKeyPath: "name", options: NSKeyValueObservingOptions.Initial, context: nil)
        toBeObservedClass?.addObserver(self, forKeyPath: "age", options: .New, context: nil)
        toBeObservedClass?.updatingValues()
    }
Here in this particular code we are assigning the textFields value to the globally declared values "name1 && age1" && then adding the observer for the properties from toBeObservedClass.swift class i.e. for name && age properties. In final line we are calling the updatingValues function which will update the values of properties that we will be observing. Now override a superclass method which will execute when the values of properties "name && age" from toBeObserved.swift class.

    override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
        println("in observe value for key path method \(toBeObservedClass!.name) && \(toBeObservedClass!.age)")
    }

All this function do is printing the updated values of the observed properties to console this will be called two times because we added observer for two properties.

I hope you enjoyed it guys......

No comments:

Post a Comment