O'Reilly logo

iOS Swift Game Development Cookbook, 3rd Edition by Paris Buttfield-Addison, Jonathon Manning

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

5.1 Storing Structured Information

Problem

You want to store and load your game’s information in a way that produces data that’s easy to read and write.

Solution

Make the objects that you want to store and load conform to the Codable class, and use one of the Encoder and Decoder classes to convert the objects to raw data that you can save and load.

For example, let’s assume that you want to store a saved game. Saved games contain three things: the level number the player is on, the name of the player, and the set of achievements that they’ve earned in this game. The achievements themselves are represented as an enumeration:

// The list of achievements that the player can get.
enum Achievements : String, Codable {
    case startedPlaying
    case finishedGameInTenMinutes
    case foundAllSecretRooms
}

// The data that represents a saved game.
class SavedGame : Codable {

    var levelNumber = 0
    var playerName = ""

    var achievements : Set<Achievements> = []
}

let savedGame = SavedGame()

// Store some data
savedGame.levelNumber = 3
savedGame ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required