我正在关注一个名为“Swift Tutorial for iOS : NSFileManager Persisting Data”的教程,我在 29 分钟左右或之后遇到了一个错误。当我尝试在 iOS 模拟器上运行它时,我收到以下错误:
由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[setValue:forUndefinedKey:]:此类与键 theLoadMethod 的键值编码不兼容。”
显然基于错误,我认为问题出在我的theLoadMethod
. 这是我在 ViewController 中作为该项目的一部分编写的所有代码:
let theDocumentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let theFileName = "/theUserFile.txt"
let thePath = theDocumentsFolder.stringByAppendingString(theFileName)
class ViewController: UIViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var ageTextField: UITextField!
@IBOutlet weak var theLabel: UILabel!
// The save method
@IBAction func theSaveMethod(sender: AnyObject) {
var name = nameTextField.text
var lastName = lastNameTextField.text
var age = ageTextField.text
var theString = "The user's information is: \(name), \(lastName), \(age)"
let theFileManager = NSFileManager.defaultManager()
if !theFileManager.fileExistsAtPath(thePath) {
var writeError:NSError?
let fileToBeWritten = theString.writeToFile(thePath, atomically: true, encoding: NSUTF8StringEncoding, error: &writeError)
if writeError == nil {
println("No errors. Added: \(theString)")
} else {
println("Encountered an error. Error is: \(writeError)")
}
} else {
println("File already exists")
}
nameTextField.resignFirstResponder()
lastNameTextField.resignFirstResponder()
ageTextField.resignFirstResponder()
}
@IBAction func theLoadMethod(sender: AnyObject) {
let infoFromFile:String = String.stringWithContentsOfFile(thePath, encoding: NSUTF8StringEncoding, error: nil)!
theLabel.text = infoFromFile
}
有什么我做错了吗?据我所知,我在屏幕上的所有 iOS 元素都已正确命名和链接。