Chapter 5. Data Storage

Games are apps, and apps run on data. Whether it’s just resources that your game loads or saved-game files that you need to store, your game will eventually need to work with data stored on the flash chips that make up the storage subsystems present on all iOS devices.

In this chapter, you’ll learn how to convert objects into saveable data, how to work with iCloud, how to load resources without freezing up the rest of the game, and more.

Saving the State of Your Game

Problem

You want game objects to be able to store their state, so that it can be loaded from disk.

Solution

Make your objects conform to the NSCoding protocol, and then implement encodeWithCoder: and initWithCoder:, like so:

- (void) encodeWithCoder:(NSCoder*) coder {
    [coder encodeObject:self.objectName forKey:@"name"];
    [coder encodeInt:self.hitPoints forKey:@"hitpoints"];
}

- (id) initWithCoder:(NSCoder*)coder {

    // note: not [super initWithCoder:coder]!
    self = [super init];

    if (self) {
        self.objectName = [coder decodeObjectForKey:@"name"];
        self.hitPoints = [coder decodeIntForKey:@"hitpoints"];
    }

}

When you want to store this information into an NSData object, for saving to disk or somewhere else, you use the NSKeyedArchiver:

GameObject* gameObject = ... // an object that conforms to NSCoder

NSData* archivedData = [NSKeyedArchiver archivedDataWithRootObject:gameObject];

// Save archivedData somewhere

If you have an NSData object that contains information encoded by NSKeyedArchiver, you can convert it back ...

Get iOS Game Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.