Skip to content

Instantly share code, notes, and snippets.

@eito
Last active August 29, 2015 14:04
Show Gist options
  • Save eito/0887c39a868e8144a3a1 to your computer and use it in GitHub Desktop.
Save eito/0887c39a868e8144a3a1 to your computer and use it in GitHub Desktop.
// Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
class Foo: NSObject {
public var changingProperty: Int = 0
public func change() {
changingProperty++
}
init() {
// println("some foo inited")
}
override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafePointer<()>) {
if keyPath == "changingProperty" {
println("changed 'changingProperty' to new value: \(change[NSKeyValueChangeNewKey])")
println("changed 'changingProperty' from old value: \(change[NSKeyValueChangeOldKey])")
println("Change dictionary in observer \(change)")
} else {
println("not changed")
}
}
}
// sends 1 notification, with new value only
var f = Foo()
var g = Foo()
f.change()
f.addObserver(g, forKeyPath: "changingProperty", options: .New, context: nil)
f.change()
println()
// sends 1 notification with new value and old value
var h = Foo()
var i = Foo()
h.change()
h.addObserver(i, forKeyPath: "changingProperty", options: .New | .Old, context: nil)
h.change()
println()
// sends 2 notifications with new value...
// it sends a notification for the first call to change() even though that was before the observer was added
var j = Foo()
var k = Foo()
j.change()
j.addObserver(k, forKeyPath: "changingProperty", options: .New | .Initial | .Old, context: nil)
j.change()
/*
.Initial just specifies the notification should be sent to the observer immediately, before the observer's registration method even returns.
this in a playground yields the following output:
changed 'changingProperty' to new value: Optional(2)
changed 'changingProperty' from old value: nil
Change dictionary in observer [kind: 1, new: 2]
changed 'changingProperty' to new value: Optional(2)
changed 'changingProperty' from old value: Optional(1)
Change dictionary in observer [kind: 1, old: 1, new: 2]
changed 'changingProperty' to new value: Optional(1)
changed 'changingProperty' from old value: nil
Change dictionary in observer [kind: 1, new: 1]
changed 'changingProperty' to new value: Optional(2)
changed 'changingProperty' from old value: Optional(1)
Change dictionary in observer [kind: 1, old: 1, new: 2]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment