gpt4 book ai didi

ios - NSUser Defaults - 将 3 个变量保存在一起然后获取

转载 作者:行者123 更新时间:2023-11-30 13:02:04 25 4
gpt4 key购买 nike

我在我的应用中使用 NSUserDefaults 进行持久存储。在这种游戏中,游戏结束后,必须存储得分以及日期和名称(由用户输入),然后将其显示在表格 View 中。到目前为止我的代码是:

import UIKit

class LeaderboardVC: UIViewController, UITableViewDataSource, UITableViewDelegate {

var finishedGame = 0
var gameScore:Int! = 0
var name:String!
var date:String!
var score:Int!
var scoreData = [NSArray]()
var defaults = UserDefaults.standard

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
super.viewDidLoad()

if finishedGame == 1{
saveNew()
}

self.tableView.delegate = self
self.tableView.dataSource = self


}

override func viewWillAppear(_ animated: Bool) {

self.navigationController?.isNavigationBarHidden = false
self.navigationItem.hidesBackButton = true



}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}

func saveNew() {

let enterNameAlert = UIAlertController(title: "Please Enter Your Name", message: "This will be used to place you in the leaderboards", preferredStyle: .alert)

enterNameAlert.addTextField { (textField:UITextField) -> Void in
textField.placeholder = "Name"
textField.autocapitalizationType = UITextAutocapitalizationType.words
textField.autocorrectionType = UITextAutocorrectionType.no
textField.clearsOnBeginEditing = true
textField.clearsOnInsertion = true
textField.clearButtonMode = UITextFieldViewMode.always
textField.keyboardType = UIKeyboardType.default

}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (action:UIAlertAction) in

let currentTime = Date()
let timeFormatter = DateFormatter()
timeFormatter.locale = Locale.current
timeFormatter.dateFormat = "HH:mm dd/MM/yy"
let convertedTime = timeFormatter.string(from: currentTime) //date
let enteredName = enterNameAlert.textFields?.first?.text //name

// set object of date,name and score here
}

enterNameAlert.addAction(cancelAction)
enterNameAlert.addAction(confirmAction)
self.present(enterNameAlert, animated: true, completion: nil)

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! LeaderBoardCell

cell.dateLabel?.text =
cell.dateLabel.adjustsFontSizeToFitWidth = true
cell.scoreLabel?.text =
cell.scoreLabel.adjustsFontSizeToFitWidth = true
cell.nameLabel?.text =
cell.nameLabel.adjustsFontSizeToFitWidth = true

return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return scoreData.count
}

func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
}

单元格中有 3 个标签,分别对应必须显示的 3 个值。如何使用 NSUserDefaults 设置这些值(它们必须在一起,例如 Score:500 与 name:John 等)?

编辑 - 新代码

import UIKit

LeaderboardVC 类:UIViewController、UITableViewDataSource、UITableViewDelegate {

var finishedGame = 0
var gameScore:Int! = 0
var defaults = UserDefaults.standard
var newUserArray = NSMutableArray()

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
super.viewDidLoad()

if finishedGame == 1{
saveNew()
}

self.tableView.delegate = self
self.tableView.dataSource = self


}

override func viewWillAppear(_ animated: Bool) {

self.navigationController?.isNavigationBarHidden = false
self.navigationItem.hidesBackButton = true



}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}

func saveNew() {

let enterNameAlert = UIAlertController(title: "Please Enter Your Name", message: "This will be used to place you in the leaderboards", preferredStyle: .alert)

enterNameAlert.addTextField { (textField:UITextField) -> Void in
textField.placeholder = "Name"
textField.autocapitalizationType = UITextAutocapitalizationType.words
textField.autocorrectionType = UITextAutocorrectionType.no
textField.clearsOnBeginEditing = true
textField.clearsOnInsertion = true
textField.clearButtonMode = UITextFieldViewMode.always
textField.keyboardType = UIKeyboardType.default

}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (action:UIAlertAction) in

let currentTime = Date()
let timeFormatter = DateFormatter()
timeFormatter.locale = Locale.current
timeFormatter.dateFormat = "HH:mm dd/MM/yy"
let convertedTime = timeFormatter.string(from: currentTime)
let enteredName = enterNameAlert.textFields?.first?.text

let newUserData = self.defaults.object(forKey: "UserData") as! NSArray
let newUserArray = NSMutableArray(array: newUserData)

let newUserRecord = [
"Name" : enteredName!,
"Score" : String(self.gameScore),
"Date" : convertedTime
] as [String : String]

newUserArray.add(newUserRecord)
self.defaults.set(newUserArray, forKey: "UserData")
self.defaults.synchronize()
print(newUserArray)
print("hello")
print(self.defaults)


}

enterNameAlert.addAction(cancelAction)
enterNameAlert.addAction(confirmAction)
self.present(enterNameAlert, animated: true, completion: nil)

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! LeaderBoardCell
let userData = defaults.object(forKey: "UserData") as! NSArray

cell.dateLabel?.text = "Date: \(((userData.object(at: indexPath.row) as! [String:Any])["Date"] as! String))"
cell.dateLabel.adjustsFontSizeToFitWidth = true
cell.scoreLabel?.text = "Score: \(((userData.object(at: indexPath.row) as! [String:Any])["Score"] as! String))"
cell.scoreLabel.adjustsFontSizeToFitWidth = true
cell.nameLabel?.text = "Name: \(((userData.object(at: indexPath.row) as! [String:Any])["Name"] as! String))"
cell.nameLabel.adjustsFontSizeToFitWidth = true

return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return newUserArray.count
}

func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

}

最佳答案

您可以将字典设置为 UserDefaults(即一次设置 3 个值)。要制作排行榜,您需要将此字典保存在数组中。

let scoreDict: [String : Any] = ["name": "John", "score": 500, "date": NSDate()]
let defaults = UserDefaults.standard

let scoresKey = "scores"

var currentScores: [Any] = defaults.array(forKey: scoresKey) ?? []
currentScores.append(scoreDict)

defaults.set(currentScores, forKey: scoresKey)
defaults.synchronize()

关于ios - NSUser Defaults - 将 3 个变量保存在一起然后获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39810307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com