Game Development Reference
In-Depth Information
Listing 7-11 . Creating a single instance of the class and returning it
+(GameState*) sharedGameState
{
static GameState* sharedInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[GameState alloc] init];
});
return sharedInstance;
}
Note This version of creating and returning a singleton instance is compliant
with ARC. You may have seen Objective-C class singletons done differently on
the Internet. Those refer to outdated variants, typically predating ARC, which
shouldn't be used and may not even work anymore.
First, this method declares two static (global) variables. Whether you place them in-
side the method definition or above and outside doesn't make a difference for static
variables. If it bothers you that they are declared inside the method because that makes
them seem like local variables, move them above the method definition. Either way is
fine, and in both cases both variables will be initialized to 0 ( nil ) by default because they
are declared static .
The sharedInstance stores the reference to the single class instance, while the
onceToken with its funny data type dispatch_once_t is nothing else but an integer
variable of type long .
The dispatch_once method runs a block once and only once. The &onceToken
means to take the address of the onceToken variable; in other words, a pointer to
onceToken is passed in. Only if onceToken is 0 will the block run, and when dis-
patch_once has run the block once, it will change onceToken to a non-zero value.
The block itself simply allocates and initializes an instance of the class via the familiar
alloc / init sequence and assigns the created instance to the static sharedIn-
stance , which retains the instance indefinitely. Any other time the
sharedGameState method runs, the block does not run again and the already existing
sharedInstance is returned.
Search WWH ::




Custom Search