Sunday, July 27, 2008

Vlad the Impaler

This post is adapted from the example in the first section of the Apple Bindings docs, at the end of that section, which introduces Vlad, Attila and Co. and their weapons. (This is not about the real Vlad, whose descriptor was apparently well-deserved). We have a Table View that displays three combatants: Maximus (ancient), George (colonial), and Neo (modern). Each combatant has an appropriate choice of weaponry, displayed with a popup button. The code is pretty standard. There is a combatant class which keeps track of its name, possible weapons, and the current selected Weapon:

class Combatant(NSObject):
weaponL = objc.ivar('weaponL')
name = objc.ivar('name')
selectedWeapon = objc.ivar('selectedWeapon')

def init(self): return self

def initWithName_Kind_(self, name, kind):
self = self.init() = name
if kind == 'ancient':
self.weaponL = ['sword','axe']
self.selectedWeapon = 'axe'
elif kind == 'colonial':
self.weaponL = ['cannon','musket']
self.selectedWeapon = 'cannon'
self.weaponL = ['drone','laser']
self.selectedWeapon = 'drone'
return self

In the AppDelegate's init method, we instantiate three Combatants (one from each era), and save them in a list called combatantL:

class PyFightAppDelegate(NSObject):
combatantL = objc.ivar('combatantL')

def init(self):
Maximus = Combatant.alloc().initWithName_Kind_(
George = Combatant.alloc().initWithName_Kind_(
Neo = Combatant.alloc().initWithName_Kind_(
self.combatantL = [Maximus, George, Neo]
NSLog("%s" % self.combatantL)
return self

The bindings are set up as shown in the tutorial:

1. Combatant controller => AppDelegate => => combatantL
2. Window title => Combatant controller => selection => name
3. Table Column => Combatant controller => arrangedObjects => name

4. Weapon controller => Combatant controller => selection => weaponL
5. Pop Up Button => Value => Weapon controller => arrangedObjects
6. Pop Up Button => Selected Object => Combatant controller => selection => selectedWeapon.

No comments: