Key Value Coding or KVC is a very important part of Cocoa. Accessing these properties can be a kludge though - you have to use setValue_forKey_(value, key) and valueForKey_(key) which is quite verbose. Luckily, PyObjC has a nice shortcut: a single underscore.

from Quartz import CALayer 
# CALayer accepts arbitrary properties, perfect for testing!
l = CALayer.layer()
l.setValue_forKey_('value1', 'key1')
v = l.valueForKey_('key1')
assert v == 'value1'

l._.key1 = 'value2'
v = l._.key1
assert v == 'value2'
v2 = l.valueForKey_('key1')
assert v2 == 'value2'

This is not very discoverable so I thought I'd put it up here in case anyone is wondering if there's a shortcut for key-value coding in PyObjC.

Note: CALayer accepts arbitrary properties but I've found that things like bounds, frame and position work best if you use directly setBounds_, setFrame_ and setPosition_. I haven't looked deeply into it though.

March 31, 2009, 9:59 p.m. More (142 words) 1 comment Feed
Previous entry: Python programmers needed
Next entry: Book heads-up: iPhone in Action

Comments

1

Comment by Elepemopy , 2 years, 9 months ago :

nice, really nice!


This post is older than 30 days and comments have been turned off.