我正在使用Xcode 6中的swift开发一款游戏。但我无法弄清楚我是如何添加高分的,这是我唯一需要添加到游戏中的东西。我试着在这里听一些答案。
我添加了一个名为HighScore.swift的新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!")
}
} }
我创建了一个新文件GameViewController.swift
并在Game View Controller类中插入了这段代码:UIViewController:
class View Controller: UIViewController, UITextFieldDelegate {
were Score = High Score ()
override viewDidLoad func () {
super.viewDidLoad ()
Score.highScore = 100
Save High Score (). Archive High Score (high score: Score)
was retrievedHighScore = Save High Score (). RetrieveHighScore () as High Score
System.out.println (retrievedHighScore.highScore)
}
}
但后来我得到了这个错误:
SaveHighScore does not have a member named
RetriveHighScore`
有人可以帮我吗?
抱歉我的英语不好。
此致 HH
答案 0 :(得分:2)
我是对的,您是否从教程中复制了游戏的其他部分?
如果是这种情况,我强烈建议您在尝试之前学习一些基础知识。您使用的是System.out.println
,这显然是Java代码。
我知道那种感觉。你会在应用程序商店中看到其他游戏,并希望自己构建一个游戏。(也许是下一个Flappy Bird)。但是你必须慢慢开始learn the basics.
因为变量中有空格等错误,使用was
或were
代替var
等等。这些是您需要了解的基础知识。所以我建议你以前从基础教程中学习。
但我会为您解决错误,以便您有非错误代码。但是,如果你能使它工作,我不会,因为有代码,我不明白为什么你在那里。
重要强>: 代码不起作用,不起作用。我试图解决尽可能多的错误,但是它不可能使它工作,因为你调用的方法在你的类中没有实现。
import UIKit
//ViewController has to be written together without spaces
class ViewController: UIViewController, UITextFieldDelegate {
//use always var and not were and use lowercase variables
var score = HighScore()
//not override viewDidLoad func
override func viewDidLoad() {
super.viewDidLoad ()
score.highScore = 100
//create an instance of your SaveHighscore class
var saveHighscore = SaveHighScore()
//why the spaces?? add the score and not (high score: Score) that's how you write it in the function
saveHighscore.ArchiveHighScore(score)
//again var and not was
//There is no function "RetrieveHighScore" so this line isn't possible
var retrievedHighScore = Save High Score ().RetrieveHighScore () as HighScore
//System.out.println is Java
System.out.println (retrievedHighScore.highScore)
}
}