關於您的按鈕,您可以創建可以存儲的對象數組。請參閱下面的NSCoding的使用。
類,我定義對象 - 例如從比賽中我寫道:
import Foundation
class ButtonStates: NSObject {
var sign: String = "+"
var level: Int = 1
var problems: Int = 10
var time: Int = 30
var skipWrongAnswers = true
func encodeWithCoder(aCoder: NSCoder!) {
aCoder.encodeObject(sign, forKey: "sign")
aCoder.encodeInteger(level, forKey: "level")
aCoder.encodeInteger(problems, forKey: "problems")
aCoder.encodeInteger(time, forKey: "time")
aCoder.encodeBool(skipWrongAnswers, forKey: "skipWrongAnswers")
}
init(coder aDecoder: NSCoder!) {
sign = aDecoder.decodeObjectForKey("sign") as String
level = aDecoder.decodeIntegerForKey("level")
problems = aDecoder.decodeIntegerForKey("problems")
time = aDecoder.decodeIntegerForKey("time")
skipWrongAnswers = aDecoder.decodeBoolForKey("skipWrongAnswers")
}
override init() {
}
}
類,我歸檔和檢索這些對象:從視圖控制器獲取數據的
import Foundation
class ArchiveButtonStates:NSObject {
var documentDirectories:NSArray = []
var documentDirectory:String = ""
var path:String = ""
func ArchiveButtons(#buttonStates: ButtonStates) {
documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
documentDirectory = documentDirectories.objectAtIndex(0) as String
path = documentDirectory.stringByAppendingPathComponent("buttonStates.archive")
if NSKeyedArchiver.archiveRootObject(buttonStates, toFile: path) {
//println("Success writing to file!")
} else {
println("Unable to write to file!")
}
}
func RetrieveButtons() -> NSObject {
var dataToRetrieve = ButtonStates()
documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
documentDirectory = documentDirectories.objectAtIndex(0) as String
path = documentDirectory.stringByAppendingPathComponent("buttonStates.archive")
if let dataToRetrieve2 = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? ButtonStates {
dataToRetrieve = dataToRetrieve2 as ButtonStates
}
return(dataToRetrieve)
}
}
例如:
let buttonStates = ArchiveButtonStates().RetrieveButtons() as ButtonStates
存儲來自ViewController的數據的示例:
ArchiveGameData().ArchiveResults(dataSet: gameDataArray)
UIButton和AnyObject都沒有屬性'owner',所以你在這裏期待什麼? – matt 2014-10-31 04:14:05
@matt,「owner」只是任何用戶定義的密鑰。主要問題是如何使用.setValue和。valueForKey方法是否可用(編譯)爲AnyObject? – yjsa 2014-11-01 13:40:44
你正在使用它們就好。這就是爲什麼你的應用程序編譯。但是,當你的應用程序運行時,這是事實證明,沒有這樣的關鍵。正如我在下面的回答中所說的,對於UIButton或AnyObject沒有「用戶定義的鍵」。 – matt 2014-11-01 15:26:29