the_critic
the_critic

Reputation: 12820

Retrieving data from singleton in a more clever way ?

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 ...

Upvotes: 1

Views: 118

Answers (2)

Phillip Mills
Phillip Mills

Reputation: 31016

If it's just the repetitive typing that you're trying to avoid, you could use the old C way...

#define GAME_STATE [GameStateSingleton sharedMySingleton]

...and then...

int localValue = [GAME_STATE property];

Upvotes: 0

DrummerB
DrummerB

Reputation: 40211

You don't need an instance variable for that. You could just write a shortcut function like this:

- (int)sharedHealth {
    return [[GameStateSingleton sharedMySingleton] getSharedHealth];
}

And where ever you need that value, you call [self sharedHealth].

You could also use a preprocessor macro instead. Just define this:

#define SharedHealth [[GameStateSingleton sharedMySingleton] getSharedHealth]

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.

Upvotes: 2

Related Questions