tags:

views:

191

answers:

1

I've got this code in my viewController.m file

- (void)viewDidLoad {
    [super viewDidLoad];
    GameLogic *_game = [[GameLogic alloc] init];
    [_game initGame];

    .......
}

GameLogic is another class which I created. in the same viewController.m file, I have got another function

- (void)test {
    if([_game returnElecFence]) //[_game returnsElecFence] causes the error
    {
        NSLog(@"YES");
    }
    else {
        NSLog(@"NO");
    }
.......
}

Problem is, whenever the test function is called, I get an error saying '_game' undeclared. I tried putting the GameLogic init code in the .h file and on top of the @implementation to make it global but every method I tried resulted in a worse error. TIA to anyone who can suggest some ideas to clear this error up

+1  A: 

_game is a local variable. Its scope is only the method in which it's declared (viewDidLoad in this case).

You need to make _game a global variable, or better yet, an instance variable of your viewController class so that it can be accessed by all methods of the class.

Wade Williams
how can I do that?I tried putting GameLogic *_game = [[GameLogic alloc] init]; above @implementation instead and I got a error: initializer element is not constant.
That's not a variable declaration, that's code. You can't just stick code where ever you feel like.Create a GameLogic *_game; instance variable in your interface section, and then change the viewDidLoad to just say:_game = [[GameLogic alloc] init];
Wade Williams
Ok, I added the GameLogic *_game; in the interface section and initialize it in viewDidLoad. But now I got an extra error in the interface section pointing to the GameLogic *_game; error: Expected specifier-qualifier-list before 'GameLogic'
You're likely not importing the header file containing the class definition for GameLogic.
Wade Williams