Last active
September 20, 2016 13:48
-
-
Save Pyroh/6e432a229ff926b30d23 to your computer and use it in GitHub Desktop.
Handy NSObject extension to propagate a value through bindings. Yep, juste like any Cocoa control. OSX only (no bindings on iOS)
This file contains hidden or 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
import Cocoa | |
fileprivate func nullableToOptionnal(value: Any?) -> Any? { | |
return value is NSNull ? nil : value | |
} | |
public extension NSObject { | |
public func propagateBoundValue(value: AnyObject?, forBinding key: String) { | |
guard let info = self.infoForBinding(key) else { return } | |
guard let boundObject = nullableToOptionnal(value: info[NSObservedObjectKey]) as? NSObject, | |
let boundKeyPath = nullableToOptionnal(value: info[NSObservedKeyPathKey]) as? String | |
else { | |
NSException().raise() | |
return | |
} | |
if let opt = info[NSOptionsKey] as? [String: AnyObject], let transformer = nullableToOptionnal(value: opt[NSValueTransformerBindingOption]) as? ValueTransformer ?? | |
(opt[NSValueTransformerNameBindingOption] as? String).flatMap({ | |
ValueTransformer(forName: NSValueTransformerName(rawValue: $0)) | |
}), NSClassFromString(transformer.className)!.allowsReverseTransformation() { | |
boundObject.setValue(transformer.reverseTransformedValue(value), forKeyPath: boundKeyPath) | |
} else { | |
boundObject.setValue(value, forKeyPath: boundKeyPath) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment