vinhnx / swift_learning_notes

Notes from learning Swift
https://github.com/vinhnx/swift_learning_notes/issues
0 stars 0 forks source link

Swift KVO example #4

Open vinhnx opened 8 years ago

vinhnx commented 8 years ago

A quick example for how to use Foundation style KVO from Swift. (Official documentation from Apple is forthcoming.)

https://gist.github.com/correia/001923bc420b942f9865

//
//  Swift-KVO
//
//  Created by Jim Correia on 6/5/14.
//  Copyright (c) 2014-2015 Jim Correia. All rights reserved.
//
//  Update: 6/17/2014
//
//  KVOContext has gone away; use the same idiom you'd use from Objective-C for the context
//
//  Update 6/10/2015
//
//  Updated for Swift 2
//  Use dynamic on observable properties

import Foundation

typealias KVOContext = UInt8
var MyObservationContext = KVOContext()

class Observer: NSObject {
    func startObservingPerson(person: Person) {
        let options = NSKeyValueObservingOptions([.New, .Old])
        person.addObserver(self, forKeyPath: "firstName", options: options, context: &MyObservationContext)
        person.addObserver(self, forKeyPath: "lastName", options: options, context: &MyObservationContext)
    }

    func stopObservingPerson(person: Person) {
        person.removeObserver(self, forKeyPath: "firstName", context: &MyObservationContext)
        person.removeObserver(self, forKeyPath: "lastName", context: &MyObservationContext)
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        guard keyPath != nil else {
            super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
            return
        }

        switch (keyPath!, context) {
        case("firstName", &MyObservationContext):
            print("First name changed: \(change)")

        case("lastName", &MyObservationContext):
            print("Last name changed: \(change)")

        case(_, &MyObservationContext):
            assert(false, "unknown key path")

        default:
            super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
        }
    }
}

class Person: NSObject {
    dynamic var firstName: String?
    dynamic var lastName: String?
}

let person = Person()

let observer = Observer()

observer.startObservingPerson(person)

person.firstName = "Jim"
person.lastName = "Correia"

observer.stopObservingPerson(person)