Saving highscores with NSUserDefaults

前端 未结 1 1108
难免孤独
难免孤独 2021-01-15 19:35

I\'m trying to save the highscore of my game. I\'m trying to do this via NSUserDefaults. This is the code I\'m using:

//To save highest score
va         


        
1条回答
  •  星月不相逢
    2021-01-15 19:59

    Use NSCoding. Create a Swift file "HighScore"

    import Foundation
    
    class HighScore: NSObject {
    
        var highScore: Int = 0
    
        func encodeWithCoder(aCoder: NSCoder!) {
               aCoder.encodeInteger(highScore, forKey: "highScore")
        }
    
        init(coder aDecoder: NSCoder!) {
            highScore = aDecoder.decodeIntegerForKey("highScore")
        }
    
        override init() {
        }
    }
    
    class SaveHighScore:NSObject {
    
        var documentDirectories:NSArray = []
        var documentDirectory:String = ""
        var path:String = ""
    
        func ArchiveHighScore(#highScore: HighScore) {
            documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
            documentDirectory = documentDirectories.objectAtIndex(0) as String
            path = documentDirectory.stringByAppendingPathComponent("highScore.archive")
    
            if NSKeyedArchiver.archiveRootObject(highScore, toFile: path) {
                println("Success writing to file!")
            } else {
                println("Unable to write to file!")
            }
        }
    
        func RetrieveHighScore() -> NSObject {
            var dataToRetrieve = HighScore()
            documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
            documentDirectory = documentDirectories.objectAtIndex(0) as String
            path = documentDirectory.stringByAppendingPathComponent("highScore.archive")
            if let dataToRetrieve2 = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? HighScore {
                dataToRetrieve = dataToRetrieve2
            }
            return(dataToRetrieve)
        }
    }
    

    Then for your ViewController:

       import UIKit
    
    
        class ViewController: UIViewController, UITextFieldDelegate {
            var Score = HighScore()
    
            override func viewDidLoad() {
                super.viewDidLoad()
    
            Score.highScore = 100
            SaveHighScore().ArchiveHighScore(highScore: Score)
            var retrievedHighScore = SaveHighScore().RetrieveHighScore() as HighScore
            println(retrievedHighScore.highScore)
    
            }
        }
    

    0 讨论(0)
提交回复
热议问题