Skip to content

Instantly share code, notes, and snippets.

@ketzusaka
Created July 16, 2015 17:39
Show Gist options
  • Select an option

  • Save ketzusaka/acedad5c25e6db1acadd to your computer and use it in GitHub Desktop.

Select an option

Save ketzusaka/acedad5c25e6db1acadd to your computer and use it in GitHub Desktop.
Fancy ObserverContext
import Foundation
public class ObserverContext: NSObject {
public let keyPath: String
public let options: NSKeyValueObservingOptions
public var context = 0
public init(keyPath: String, options: NSKeyValueObservingOptions = nil) {
self.keyPath = keyPath
self.options = options
}
}
public extension NSObject {
public func addObserver(observer: NSObject, context: ObserverContext) {
addObserver(observer, forKeyPath: context.keyPath, options: context.options, context: &context.context)
}
public func removeObserver(observer: NSObject, context: ObserverContext) {
removeObserver(observer, forKeyPath: context.keyPath, context: &context.context)
}
}
// USAGE:
class ViewController: UIViewController {
private let contentSizeContext = ObserverContext(keyPath: "contentSize")
private lazy var scrollView: UIScrollView = { return UIScrollView() }()
override func viewDidLoad() {
super.viewDidLoad()
scrollView.addObserver(self, context: contentSizeContext)
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
switch context {
case &contentSizeContext.context:
print(scrollView.contentSize)
default:
super.observerValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
deinit {
if isViewLoaded() {
scrollView.removeObserver(self, context: contentSizeContext)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment