Skip to content

Instantly share code, notes, and snippets.

@venkatperi
Created August 11, 2014 18:38
Show Gist options
  • Save venkatperi/1352e22a9e4c92b29fc7 to your computer and use it in GitHub Desktop.
Save venkatperi/1352e22a9e4c92b29fc7 to your computer and use it in GitHub Desktop.
KVOTests
//
// KVOTests.swift
// SwiftStuff
//
// Created by Venkat Peri on 8/11/14.
// Copyright (c) 2014 vperi. All rights reserved.
//
import Cocoa
import XCTest
class KVOTests: XCTestCase {
class Publisher : NSObject {
dynamic var someProperty : Int = 100 { didSet { println("didSet \(someProperty)") } }
override var description: String { return "Publisher:{someProperty: \(someProperty)}" }
}
class Subscriber : NSObject {
var callback: ()->()
init(callback: ()->()) {
self.callback = callback
}
override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!,
change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<()>) {
println("Subscriber: observeValueForKey: \(keyPath), \(object)")
self.callback()
}
}
var pub: Publisher!
var sub: Subscriber!
override func setUp() {
super.setUp()
pub = Publisher()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testCallbackOnChange() {
var called = false
sub = Subscriber(callback: { called = true } )
pub.addObserver(sub, forKeyPath: "someProperty", options: NSKeyValueObservingOptions.New, context: nil)
XCTAssert(called == false, "Shouldn't receive initial callback")
pub.someProperty = 101
XCTAssert(called, "Should receive callback on new value")
println("printing pub: \(pub)")
println("printing pub.description: \(pub.description)")
pub.removeObserver(sub, forKeyPath: "someProperty")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment