Skip to content

Instantly share code, notes, and snippets.

@veeneck
Last active November 4, 2016 15:46
Show Gist options
  • Save veeneck/98c0c46e70ba533c0c08 to your computer and use it in GitHub Desktop.
Save veeneck/98c0c46e70ba533c0c08 to your computer and use it in GitHub Desktop.
Save game in SpriteKit
class GameData : NSObject, NSCoding {
/// Data to save
var variableA : Int = 1
var variableB : Int = 2
var variableC : Int = 3
/// Create of shared instance
class var sharedInstance: GameData {
struct Static {
static var instance: GameData?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
var gamedata = GameData()
if let savedData = GameData.loadGame() {
gamedata = savedData
}
Static.instance = gamedata
}
return Static.instance!
}
override init() {
super.init()
}
required init(coder: NSCoder) {
super.init()
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(GameData.sharedInstance, forKey: "GameData")
}
/// Loading and saving courtesy of:
/// http://www.thinkingswiftly.com/saving-spritekit-game-data-swift-easy-nscoder/
class func loadGame() -> GameData? {
// load existing high scores or set up an empty array
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0] as String
let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")
let fileManager = NSFileManager.defaultManager()
// check if file exists
if !fileManager.fileExistsAtPath(path) {
// create an empty file if it doesn't exist
if let bundle = NSBundle.mainBundle().pathForResource("DefaultFile", ofType: "plist") {
fileManager.copyItemAtPath(bundle, toPath: path, error:nil)
}
}
if let rawData = NSData(contentsOfFile: path) {
// do we get serialized data back from the attempted path?
// if so, unarchive it into an AnyObject, and then convert to an array of HighScores, if possible
if let data = NSKeyedUnarchiver.unarchiveObjectWithData(rawData) as? GameData {
return data
}
}
return nil
}
func save() {
// find the save directory our app has permission to use, and save the serialized version of self.scores - the HighScores array.
let saveData = NSKeyedArchiver.archivedDataWithRootObject(GameData.sharedInstance);
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray;
let documentsDirectory = paths.objectAtIndex(0) as NSString;
let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist");
saveData.writeToFile(path, atomically: true);
}
}
@mxcl
Copy link

mxcl commented Feb 18, 2015

As I understand, all Swift static data is wrapped in an automatic dispatch_once. Maybe I'm wrong though.

@assylman
Copy link

assylman commented Nov 4, 2016

Hello, can you write this on swift 3.0? Because in swift 3.0 removed dispatch_once_t. If it wouldn't be hard for you)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment