Game Development Reference
In-Depth Information
In Listing 10-3, we see the task
productsRequest:didReceiveResponse:
that gets called when we
have a valid set of product IDs. In this task, we simply iterate over all of the products returned and
make our buttons visible for purchasing saucers and power-ups. In this way, we make sure the user
only sees viable purchase options.
We also map each of valid product IDs to the SKProduct objects set to the application. In this way,
when the user makes a purchase, we can pull out the exact object Apple sent to us. This ensures we
are presenting good data to our users.
We have looked at how we figure out which purchases are valid. Before we look at how purchases
are actually made, we should examine the class
GameParameters
. The class
GameParameters
is
responsible for storing which products have already been purchased and which actors the user
wants in his or her game.
Driving the UI from Existing Purchases
The three buttons, shown in Figure
10-1
, allow the user to select which actors are available in the
game. The same UI allows the user to purchase new actors. In order to keep track of this information
we have created the model class
GameParameters
, whose header is shown in Listing 10-4.
Listing 10-4. GameParameters.h
@interface GameParameters : NSObject<NSCoding>
@property (nonatomic) BOOL includeAsteroids;
@property (nonatomic) BOOL includeSaucers;
@property (nonatomic) BOOL includePowerups;
@property (nonatomic, retain) NSMutableSet* purchases;
+(id)gameParameters;
+(id)readFromDefaults;
-(void)writeToDefaults;
@end
In Listing 10-4, we see the header for the class
GameParameters
. We have three
BOOL
properties
to keep track of which actors the user wants in the game. We also have an
NSMutableSet
called
purchases
that is used to store a set of product ID strings. The constructor
gameParameters
will
create a new
GameParameters
object with no purchases and only
includeAsteroids
set to true
(implementation not shown). The class task
readFromDefaults
is used to pull a
GameParameter
out of
the default
NSUserDefaults
, whereas
writeToDefaults
is used to serialize a
GameParameter
back to
the default
NSUserDefautls
. Listing 10-5 shows both
readFromDefaults
and
writeToDeafaults
.
Listing 10-5. GameParameters.m (readFromDefaults and writeToDefaults)
+(id)readFromDefaults{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSData* data = [defaults objectForKey:GAME_PARAM_KEY];
if (data == nil){
GameParameters* params = [GameParameters gameParameters];
[params writeToDefaults];