我有以下函数使用核心数据将结果转移到 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)
最佳答案
最简单的方法是在将要保存的所有内容填充到 gameResult
对象后执行类似的操作。
do {
try appDelegate.managedObjectContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}
您需要在适当的 managedObjectContext 上调用 save 以便存储对象。
解释它的苹果文档链接 here
关于ios - 如何在 Swift 的核心数据中保存多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35448033/