开发者

In objective-c , How to make variable accessible from more than one class

in cocos2d for iphone i have two classes:

1- GameScene.h class

2- Player.h class

GameScene.h has this label scoreLabel2 declared as follows

   @interface GameScene : CCLayer {
    Player* player;
    CCLabel* scoreLabel2;

and the player.h class has the following method

 -(void)updateScore{
      NSLog(@"%@",scoreLabel2);
 }

I am getting this error

          error: 'scoreLabel2' undeclared (first use in this function)

what is the best solution to that problem since I will need to use many开发者_开发技巧 objects and variables between my classes?

Many Thanks


Ahmed,

You need to have an updateScore method on your scene and then call this method from your player class. I would recommend something like this:

@interface GameScene : CCLayer {
Player* player;
CCLabel* scoreLabel2;
NSInteger score;
...
}
...
- (void) updateScoreByAmount:(NSInteger)scoreModifier;

andin the .m you would have something like:

- (void) updateScoreByAmount:(NSInteger)scoreModifier
{
    score += scoreModifier;  // scoreModifier can be positive or negative
}

then in your player class you would call this method on your scene when you want to change the score.

[myScene updateScoreByAmount:5];

This will need to be modified to suit your situation, but something like that is what you are looking for.


You can do it with [scene valueForKey:@"scoreLabel2"] but that points to a nasty problem with the design of your classes. You haven't properly declared the interface to the GameScene and there's no reference to the GameScene in the Player's updateScore method. Maybe it's just a typo, but you shouldn't be declaring whole methods in the .h file. (Not sure if this is a getter or a setter either. Normally, I'd infer that it's a getter because it doesn't have a parameter, but I don't think it's safe to assume anything about this code.) I mean this in the nicest way, but it sounds like you have a lot of fundamental work to do to understand OOP better.


The answer to your question is using Singletons. Hi have recently answered a similar question here

How to share data between separate classes in Java

you can do the same thing in Objective-C actually there should be an example int he wiki page I provide in the answer.

Bye

Andrea

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜