Sunday, October 4, 2009

Bindings: multiple controllers

The next example in our series about simple examples of bindings involves multiple controllers. I actually posted about this before, but I want to do it again. The main reason is that I still find it complicated enough that it's hard to do without looking up the answers.

We have three combatants from different eras:

• Maximus (hero of "Gladiator"), his weapons are: sword and axe.
George (father of his country), his weapons are: musket and cannon.
• Neo (in honor of "The Matrix", but not quite the same spirit), his weapons are: drone and laser.

The dull part is actually getting the data into the program. You can do it manually by using the code listed at the bottom for the App Delegate's init method. The last part will write a plist file that you could subsequently load, as discussed here. You do not actually have to do the @property and @synthesize stuff we talked about, but it's a good habit to get into. And it wouldn't hurt to have a separate class handle the data, but I haven't done that here.

The next post will actually show how to set up the bindings.

Here's a screenshot of the plist (in XCode):



And here's the code:

- (id)init {
self = [super init];
if (self == nil) return nil;

combatantList = [NSMutableArray
arrayWithCapacity:10];
NSMutableDictionary *mD;

mD = [NSMutableDictionary
dictionaryWithCapacity:3];
[mD setObject:[NSArray
arrayWithObjects:@"sword",@"axe",nil]
forKey:@"weapons"];
[mD setObject:@"Maximus"
forKey:@"name"];
[mD setObject:@"axe"
forKey:@"selectedWeapon"];
[combatantList addObject:mD];

mD = [NSMutableDictionary
dictionaryWithCapacity:3];
[mD setObject:[NSArray
arrayWithObjects:@"cannon",@"musket",nil]
forKey:@"weapons"];
[mD setObject:@"George"
forKey:@"name"];
[mD setObject:@"musket"
forKey:@"selectedWeapon"];
[combatantList addObject:mD];


mD = [NSMutableDictionary
dictionaryWithCapacity:3];
[mD setObject:[NSArray
arrayWithObjects:@"drone",@"laser",nil]
forKey:@"weapons"];
[mD setObject:@"Neo"
forKey:@"name"];
[mD setObject:@"drone"
forKey:@"selectedWeapon"];
[combatantList addObject:mD];
NSLog(@"combatantList %@", combatantList);

NSString *fn = NSHomeDirectory();
fn = [fn stringByAppendingString:
@"/Desktop/x.plist"];
[combatantList writeToFile:fn
atomically:YES];
return self;
}