If you use Cocoa Bindings and have an array of NSString
s where one entry controls a check box in your user interface, you need to provide a Value Transformer in Interface Builder.
I couldn’t find one, so I wrote one. The core are two methods:
- (id)transformedValue:(id)value
{
if(value
&& [[NSString stringWithString:value]
isEqualToString:@"1"]) {
return [NSNumber numberWithBool:YES];
} else {
return [NSNumber numberWithBool:NO];
}
}
- (id)reverseTransformedValue:(id)value
{
if([value boolValue] == YES) {
return [NSString stringWithString:@"1"];
} else {
return [NSString stringWithString:@"0"];
}
}
They convert an NSString
to a BOOL
and vice versa. This is not exactly true, as these functions work on objects and not with the native BOOL
type. To create an object that represents a boolean value, you do [NSNumber numberWithBool:YES];
.
Finally, you must register your new value transformer with your controller. I use -(id) init
for that:
[NSValueTransformer setValueTransformer:
[[JLStringToBoolValueTranformer new] autorelease]
forName: @"JLStringToBoolValueTranformer"];
You can now select the JLStringToBoolValueTranformer in the Value Transformer drop down list on the bindings pane of your checkbox.
Get the files.
If there is a more-preferred way to do this, please let me know.