Created
January 13, 2016 15:31
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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