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:
class
Monster
:
NSObject
,
NSCoding
{
// Game data
var
hitPoints
=
0
var
name
=
"GameObject"
// Initializer used when creating a brand new object
override
init
()
{
}
// Initializer used when loading the object from data
required
init
(
coder
aDecoder
:
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"
}
func
encodeWithCoder
(
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 ...
Get iOS Swift Game Development Cookbook, 2nd Edition 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.