I have some game data in my GameStateSingleton, which I don’t want to retrieve every time explicitly with [[GameStateSingleton sharedMySingleton]getVariable], so I asked myself whether it is possible to do something like that :
In the interface file of my class, GameLayer I set up properties and variables like sharedHealth.
@interface GameLayer : CCLayer
{
int sharedHealth;
}
@property (nonatomic,assign) int sharedHealth;
and of course synthesize it in the implementation.
@synthesize sharedHealth;
In the initialization of GameLayer I would like to do something like :
sharedHealth = [self getCurrentHealth];
and add the corresponding method
-(int)getCurrentHealth{
int myHealth = [[GameStateSingleton sharedMySingleton]getSharedHealth];
return myHealth;
}
Is that possible ? From what I have experienced, I just seem to get crashes. How would I achieve my goal, to not always have to call the long method, as it always retrieves the same variable? There has to be a solution for this …
You don’t need an instance variable for that. You could just write a shortcut function like this:
And where ever you need that value, you call
[self sharedHealth].You could also use a preprocessor macro instead. Just define this:
And then simply use that when you need the value.
Note, that in Objective-C you don’t call getter methods “
getVariable“, but simply “variable“. Mostly this is a convention, but if you start using KVC or KVO it’s a rule you have to follow. So it’s better to get used to it as soon as possible.