Skip to content

Instantly share code, notes, and snippets.

@mickmaccallum
Created January 13, 2016 15:31
Show Gist options
  • Save mickmaccallum/abf376fe15aee3fe7f34 to your computer and use it in GitHub Desktop.
Save mickmaccallum/abf376fe15aee3fe7f34 to your computer and use it in GitHub Desktop.
An NSObject extension which allows you to use enums as key paths for common KVO tasks.
extension NSObject {
func addObserver <RawType: RawRepresentable where RawType.RawValue == String>(observer: NSObject, forKeyPath keyPath: RawType, options: NSKeyValueObservingOptions, context: UnsafeMutablePointer<Void>) {
addObserver(observer, forKeyPath: keyPath.rawValue, options: options, context: context)
}
func removeObserver <RawType: RawRepresentable where RawType.RawValue == String>(observer: NSObject, forKeyPath keyPath: RawType) {
removeObserver(self, forKeyPath: keyPath.rawValue)
}
func removeObserver <RawType: RawRepresentable where RawType.RawValue == String>(observer: NSObject, forKeyPath keyPath: RawType, context: UnsafeMutablePointer<Void>) {
removeObserver(observer, forKeyPath: keyPath.rawValue, context: context)
}
func willChangeValueForKey <RawType: RawRepresentable where RawType.RawValue == String>(key: RawType) {
willChangeValueForKey(key.rawValue)
}
func didChangeValueForKey <RawType: RawRepresentable where RawType.RawValue == String>(key: RawType) {
didChangeValueForKey(key.rawValue)
}
}
Example:
enum OperationState: String {
case isExecuting, isFinished, isReady, isCancelled
}
thingToBeObserved?.addObserver(self,
forKeyPath: OperationState.isFinished,
options: [.Initial, .New],
context: someContext
)
thingToBeObserved?.removeObserver(self,
forKeyPath: OperationState.isFinished,
context: someContext
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment