Game Development Reference
In-Depth Information
Tip
For object references in particular, avoid having them at all in a singleton
class. Any property of type
id
or a concrete class pointer is referenced strongly
by default, preventing the object from deallocating. Since the singleton itself
will never (normally) deallocate during the runtime of the app, any object refer-
ence retained by the singleton will also practically become a permanent instance
unless explicitly set to
nil
. And if you have to set a reference to
nil
expli-
citly, you're back to how programming was before ARC—that is, manual refer-
ence counting (MRC) and manual memory management in general.
This said, in this particular case with the class being a wrapper for the already-singleton
class
NSUserDefaults
, the use of the
GameState
class is sound and justifiable. So
go ahead and create another Objective-C class in Xcode. You know the drill: right-click
the
Source
group, choose
New File
, and enter
GameState
as the name, but make it a sub-
class of
NSObject
since singletons need not be, nor should they ever be,
CCNode
sub-
classes.
After creating the class, open the
GameState.h
file and add the lines highlighted in
Listing
Listing 7-10
.
Declaring the GameState methods and properties
#import <Foundation/Foundation.h>
@interface GameState : NSObject
+(GameState*) sharedGameState;
@property CGFloat musicVolume;
@property CGFloat effectsVolume;
@end
The
sharedGameState
class is prefixed with a
+
, which makes it a class method ac-
cessible from any other class. It will return, and if necessary create, the single instance of
the
GameState
class. The properties will enable you to change and retrieve the volumes
as if they were properties of the class, when in fact they will run custom setter and getter
methods instead of referring to ivars.
the
GameState.m
file. This creates a single instance of the class if there is no instance yet.
It will then return the instance.
Search WWH ::
Custom Search