使用UserDefault在Swift中使用持久数据的排行榜来保存值



我正在尝试创建一个排行榜,但是播放器名称和分数并未永久保存,"排行榜"仅包含其文本视图中最新游戏中的数据。我尝试使ArrayofData最初保留Playername和finalsCore,而不是一个空数组,但问题仍然存在。我如何在排行榜中永久显示Playername和PlayerScore,并随着更多的人播放而添加更多名称和分数?

var finalScore = Int()
var playerName = String()
var allMyStoredData = UserDefaults.standard
var arrayOfData: [Any] = []
class secondVC: UIViewController {
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var nameTF: UITextField!
@IBOutlet weak var doneButton: UIButton!
var playerScore = 0
var arrayOfData: [Any] = []
    override func viewDidLoad() {
    super.viewDidLoad()
        scoreLabel.text = "Your score is: (finalScore)"
        loadData()
}
@IBAction func donePressed(_ sender: Any) {
    saveData()
    performSegue(withIdentifier: "toLeaderboard", sender: self)
}
func saveData () {
    playerName = nameTF.text!
    playerScore = finalScore
    arrayOfData.append(playerName)
    arrayOfData.append(playerScore)
    allMyStoredData.set(playerName, forKey: "saveTheName")
    allMyStoredData.set(playerScore, forKey: "saveTheScore")
    allMyStoredData.set(arrayOfData, forKey: "saveTheArray")

}
func loadData () {
    if let loadPlayerName:String = UserDefaults.standard.value(forKey: "saveTheName") as? String {
        playerName = loadPlayerName
    }
    if let loadTheScore:Int = UserDefaults.standard.value(forKey: "saveTheName") as? Int {
        playerScore = loadTheScore
    }
}
}

//这是排行榜的视图控制器中的代码

class leaderboardViewController: UIViewController {
    @IBOutlet weak var theTextView: UITextView!
    override func viewDidLoad() {
        super.viewDidLoad()
        theTextView.text = "((arrayOfData).map{"($0)"}.joined(separator: "          Score: "))"
    }
}

您每次使用新阵列覆盖saveTheArray项目UserDefaults

您想先获取保存的阵列,附加新游戏数据,然后重新保存如下:

//Create user defaults instance
let userDefaults = UserDefaults.standard
//User defaults key
let historicalGameDataKey = "historicalGameData"
//Fetch game data array
var historicalGameData = userDefaults.array(forKey: historicalGameDataKey)
//Create array if it is nil (i.e. very first game)
if historicalGameData == nil {
    historicalGameData = []
}
//Create game data dictionary
let gameData = [
    "playerName": playerName,
    "playerScore": playerScore
]
//Append game data dictionary to the array
historicalGameData?.append(["playerName": gameData])
//Save the updated array
userDefaults.set(historicalGameData, forKey: historicalGameDataKey

核心数据将是存储此数据的更好方法,但是此示例应使用UserDefaults解决您的问题。

相关内容

  • 没有找到相关文章

最新更新