将高分复制到可读变量以显示在标签中

时间:2015-02-10 23:15:11

标签: ios swift sprite-kit

我的高分系统需要帮助。到目前为止,我在标签上显示了receivedHighScore变量(见下文)。如果我硬编码它,它会工作并显示值,但我无法显示retrievedHighScore。即使我尝试创建一个全局变量并在显示它时使用它,我得到<TestGame.HighScore: 0x170224aa0>

如果有人可以帮助我将当前的高分counter保存到Score.HighScore或者需要去的任何地方,那就太棒了。

目前我有两个部分。 HighScore.swift包括:

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)
}
}

在我的GameViewController中我有这个:

var Score = HighScore()
var receivedHighScore = HighScore()

override func viewDidLoad() {
    super.viewDidLoad()

    SaveHighScore().ArchiveHighScore(highScore: Score)
    var retrievedHighScore = SaveHighScore().RetrieveHighScore() as HighScore
    println(retrievedHighScore)

    receivedHighScore = SaveHighScore().RetrieveHighScore() as HighScore
}

func update() {

    labelCounter.text = String(counter++)
    var highScoreYes = counter
    Score.highScore = highScoreYes-1
}

1 个答案:

答案 0 :(得分:0)

使用时获得高分:

var retrievedHighScore = SaveHighScore().RetrieveHighScore() as HighScore

retrivedHighScore设置为HighScore对象的实例。

要获得高分值,您需要访问retrivedHighScore所拥有的highScore属性:

let currentHighScore: Int=retrivedHighScore.highScore