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 init(coder:), like so:
classMonster:NSObject,NSCoding{// Game datavarhitPoints=0varname="GameObject"// Initializer used when creating a brand new objectoverrideinit(){}// Initializer used when loading the object from datarequiredinit(coderaDecoder:NSCoder){self.hitPoints=aDecoder.decodeIntegerForKey("hitPoints")// Attempt to get the object with key "name" as a string;// if we can't convert it to a string or it doesn't exist,// fall back to "No Name"self.name=aDecoder.decodeObjectForKey("name")as?String??"No Name"}funcencodeWithCoder(aCoder:NSCoder){aCoder.encodeObject(self.name,forKey:"name")aCoder.encodeInteger(self.hitPoints,forKey:"hitPoints")}}
When you want to store this information into an NSData object, for saving to disk or somewhere else, you use ...
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