views:

22

answers:

1

In my controller class, I initialize two instances of a model class (whose header is properly imported into controller class) with an NSButton. The model is really simple, just 4 members and one method - attack(). Making a silly text game!

 - (IBAction)startGame:(id)sender {

    Combatant *hero = [[Combatant alloc] init];
    Combatant *enemy = [[Combatant alloc] init];
    [console insertText:@"You have created a hero! An enemy approaches...\n"];
 }

So now I have these two objects sitting there. Or do I? Because this other button, the one that's supposed to make them fight, has no idea what hero and enemy are, or that they have a class method that makes em' fight!

- (IBAction)attack:(id)sender{

[hero attack:enemy]; //Use of undeclared identifier, blah blah.
[console insertText:@"You attack the enemy! Woah!\n"];}

I get that if I initialized those objects in the attack method, then I could use them, so I gather this is something to do with scope. But I don't like the idea of sending model objects to controller methods, that seems silly.

Let me apologize: yes, this is a stupid, high-level question about the structure of Cocoa. Sorry. But I figure one of you will know exactly what I am not doing and tell me to do it!

In short, what is the Cocoa way of doing things in this situation? Thanks in advance.

-Alec

+1  A: 

When you declare a variable in a method, it is a local variable, which means it only exists in that method. The same goes for variables you declare in functions.

If you want the variable to exist in all instance methods in the class, you need to make it an instance variable, which you do by declaring it in that { … } section in the class's @interface.

Note that any objects you store in instance variables, the instance should own. This means three things:

  1. You'll need to either retain the object (and thereby own it) or make a copy (which you will then own) before assigning it to the instance variable.
  2. Since you own it, you'll need to release it in the instance's dealloc method.
  3. If you decide to replace it with a different object, you'll need to release the former object (since you still own it) and retain or copy the new object (in order to own it).

See the Objective-C Programming Language and the Memory Management Programming Guide for more information.

Peter Hosey
Thanks Peter! That was exactly the answer I was hoping for. Having declared it as an instance variable for the controller, I can use the objects freely in that class. Thanks for taking the time. Much appreciated!
Alec Sloman