Game Development Reference
variable; it lives outside the scope of any class. That's why it is defined outside any
method, and it can be accessed in class methods like sharedLayer .
When the layer is deallocated, the sharedMultiLayerScene variable is set back
to nil to avoid crashes, because the sharedMultiLayerScene variable would be
pointing to an already released object after the dealloc method has run. Variables
declared static live on past the deallocation of a class. Using static variables to
store pointers to dynamically allocated classes requires great care to ensure that the
static variable always points to a valid object and is nil otherwise.
The reason for this semi-singleton is that you'll be using several layers, each with its
own child nodes, but you still need to somehow access the main layer. It's a very com-
fortable way to give other layers and nodes of the current scene access to the main lay-
Caution This semi-singleton works only if there is only ever one instance of
MultiLayerScene allocated at any one time. It also can't be used to initial-
ize MultiLayerScene , unlike a regular singleton class.
You grant access to the GameLayer and UserInterfaceLayer through property
the relevant part from MultiLayerScene.h .
Listing 5-6. Property Definitions for Accessing the GameLayer and UserInterfaceLay-
@property (readonly) GameLayer* gameLayer;
@property (readonly) UserInterfaceLayer* uiLayer;
The properties are defined as readonly , because we only ever want to retrieve the
layers, never set them through the property. Their implementation in Listing 5-7 is a
straightforward wrapper to the getChildByTag method, but they also perform a
safety check just in case, verifying that the retrieved object is of the correct class.
Listing 5-7. Implementation of the Property Getters