Skip to content

Instantly share code, notes, and snippets.

@Pyroh
Last active September 20, 2016 13:48
Show Gist options
  • Save Pyroh/6e432a229ff926b30d23 to your computer and use it in GitHub Desktop.
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)
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