In a Core Data entity i have a „length" attribute. I save the length in centimeters.
I want to give the user the possibility to view and edit the length in centimeters or inches. So i place a NSTextField next to a NSPopUpButton with cm and inch as choices.
What is the best way to format the NSTextField according to the choice taken by the NSPopUpButton? If reasonable for this problem i would want to work with bindings as much as possible.
I saw there are
or i could write custom code to transform the units?
What is the most elegant way to solve this problem?
If you persist the cm/in choice for the user as a per-entity choice with an attribute on the entity, you could do it with a value binding and a custom value transformer with reverse transformation on the textfield, a cm/in choice binding on the popup, and a keyPathsForValuesAffectingLength class method on the entity.
If the attribute displaysInInches-- or whatever you call it-- is registered as a keyPath that affects length's value, the custom value transformer would get called when the popup is toggled, and the text field would update.
If the cm/in choice is from user defaults (if the change is not per-instance), you could bind the popup to user defaults and have the custom value transformer take the default into consideration, but changing that popup wouldn't refresh the textfield. So I think you'd need an IBAction just to touch the instance's length.
You could add a number formatter on top of that-- especially if your value transformer transforms into NSNumber and not NSString-- but mostly for localization and number of significant digits, not for the cm/in math.