【发布时间】:2025-12-04 08:25:01
【问题描述】:
我有以下函数使用 Core Data 将结果传递给 ScoreTableViewController:
func showScore(){
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let gameResult = NSEntityDescription.insertNewObjectForEntityForName("SaveGame", inManagedObjectContext: appDelegate.managedObjectContext) as! ScoreHistory
gameResult.datePlayed = self.dateToday
gameResult.totalScore = self.scorepassed
gameResult.totalAnswered = self.numberofquestions
gameResult.totalDuration = self.totalduration
gameResult.gameStatus = self.gameStatus
self.performSegueWithIdentifier("scoreListSegue", sender: self)
}
我可以通过以下方式在 ScoreTableViewController 中显示分数:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell
if let game = fetchedResultsController!.objectAtIndexPath(indexPath) as? ScoreHistory {
cell.textLabel?.text = "Date: \(game.datePlayed!) | Score: \(game.totalScore!)/\(game.totalAnswered!) | \(game.totalDuration!) | \(game.gameStatus!)"
}
return cell
}
但是,当我重新启动应用程序时,数据不再存在。
我看过这段代码来保存“totalScore”数据:
func saveScore(saveTotalScore: String){
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("SaveGame", inManagedObjectContext: managedContext)
let totalScore = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
totalScore.setValue(saveTotalScore, forKey: "totalScore")
do {
try managedContext.save()
scoreData.append(totalScore)
}
catch {
print("error")
}
}
但是,如何保存我需要的所有数据? (例如:datePlayed、totalScore、totalAnswered、totalDuration 和 gameStatus)
【问题讨论】: