Monday, July 28, 2008


Reading through the first section of the Apple bindings tutorial, they talk about NSValueTransformers and how they could be useful with bindings. Wanting to explore, I read a bit in the documentation for the class, but struggled a before finding this. It was particularly helpful because I'm kind of hazy about class methods. The result is an app that does Fahrenheit to Celsius conversion entirely by the use of bindings and a specialized NSValueTransformer class. It is reversible. Both text fields also have formatters dropped on them. Notice that the name of the transformer in the binding is the class name.

Here is the code:

class PyX2AppDelegate(NSObject):
x = objc.ivar('x')
def setx_(self,value): x = int(value)

def awakeFromNib(self):
self.x = 98.6
self.t = MyTransformer.alloc().init()
NSLog("%s" % self.t.description())

self.t, u'MyTransformer')

class MyTransformer(NSValueTransformer):

def transformedValueClass(cls): return NSNumber
#transformedValueClass = classmethod(transformedValueClass)

def allowsReverseTransformation(cls): return True

def init(self):
self = super(MyTransformer,self).init()
return self

# Fahrenheit to Celsius
def transformedValue_(self,value):
if value is None: return None
f = float(value)
return (5.0/9.0) * (f - 32.0)

# Celsius to Fahrenheit
def reverseTransformedValue_(self,value):
if value is None: return None
f = float(value)
return ((9.0/5.0) * f) + 32.0

No comments: