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.enumAchievements:String,Codable{casestartedPlayingcasefinishedGameInTenMinutescasefoundAllSecretRooms}// The data that represents a saved game.classSavedGame:Codable{varlevelNumber=0varplayerName=""varachievements:Set<Achievements>=[]}letsavedGame=SavedGame()// Store some datasavedGame.levelNumber=3savedGame ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access