diff --git a/NSObject+BindingValue.h b/NSObject+BindingValue.h new file mode 100644 index 0000000..4e75581 --- /dev/null +++ b/NSObject+BindingValue.h @@ -0,0 +1,20 @@ +// +// NSObject+BindingValue.h +// Tags +// +// Created by Sven Weidauer on 10.06.11. +// Copyright 2011 __MyCompanyName__. All rights reserved. +// + +#import + + +@interface NSObject (BindingValue) + +- (void) setValue: (id) value forBinding: (NSString *) binding; +- (id) valueForBinding: (NSString *) binding; + +- (id) mutableArrayValueForBinding: (NSString *) binding; +- (id) mutableSetValueForBinding: (NSString *) binding; + +@end diff --git a/NSObject+BindingValue.m b/NSObject+BindingValue.m new file mode 100644 index 0000000..8eae6e8 --- /dev/null +++ b/NSObject+BindingValue.m @@ -0,0 +1,62 @@ +// +// NSObject+BindingValue.m +// Tags +// +// Created by Sven Weidauer on 10.06.11. +// Copyright 2011 __MyCompanyName__. All rights reserved. +// + +#import "NSObject+BindingValue.h" + + +@implementation NSObject (BindingValue) + +static NSValueTransformer *TransformerFromInfoDict( NSDictionary *dict ) +{ + NSDictionary *options = dict[NSOptionsKey]; + if (options == nil) return nil; + + NSValueTransformer *transformer = options[NSValueTransformerBindingOption]; + + if (transformer == nil || (id)transformer == [NSNull null]) { + transformer = nil; + NSString *name = options[NSValueTransformerNameBindingOption]; + if (name != nil && (id)name != [NSNull null]) { + transformer = [NSValueTransformer valueTransformerForName: name]; + } + } + + return transformer; +} + +- (void) setValue: (id) value forBinding: (NSString *) binding; +{ + NSDictionary *info = [self infoForBinding: binding]; + NSValueTransformer *transformer = TransformerFromInfoDict( info ); + if (transformer != nil && [[transformer class] allowsReverseTransformation]) value = [transformer reverseTransformedValue: value]; + [info[NSObservedObjectKey] setValue: value forKeyPath: info[NSObservedKeyPathKey]]; +} + +- (id) valueForBinding: (NSString *) binding; +{ + NSDictionary *info = [self infoForBinding: binding]; + id value = [info[NSObservedObjectKey] valueForKeyPath: info[NSObservedKeyPathKey]]; + NSValueTransformer *transformer = TransformerFromInfoDict( info ); + if (transformer != nil) value = [transformer transformedValue: value]; + return value; +} + +- (id) mutableArrayValueForBinding: (NSString *) binding; +{ + NSDictionary *info = [self infoForBinding: binding]; + return [info[NSObservedObjectKey] mutableArrayValueForKeyPath: info[NSObservedKeyPathKey]]; +} + +- (id) mutableSetValueForBinding: (NSString *) binding; +{ + NSDictionary *info = [self infoForBinding: binding]; + return [info[NSObservedObjectKey] mutableSetValueForKeyPath: info[NSObservedKeyPathKey]]; +} + + +@end