Skip to content

Instantly share code, notes, and snippets.

@ralfebert
Forked from correia/swift-kvo-example.swift
Last active October 18, 2020 21:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ralfebert/f6f9d625222f0ef0be02 to your computer and use it in GitHub Desktop.
Save ralfebert/f6f9d625222f0ef0be02 to your computer and use it in GitHub Desktop.
Swift 1.1: dynamic for observable properties neccessary, observeValueForKeyPath signature changed
//
// Swift-KVO
//
// Created by Jim Correia on 6/5/14.
// Copyright (c) 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
import Foundation
typealias KVOContext = UInt8
var MyObservationContext = KVOContext()
class Observer: NSObject {
func startObservingPerson(person: Person) {
let options = NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.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>) {
switch (keyPath, context) {
case("firstName", &MyObservationContext):
println("First name changed: \(change)")
case("lastName", &MyObservationContext):
println("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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment