[英]How to save multiple items in Core Data in Swift
I have the following function using Core Data to segue the results to the ScoreTableViewController: 我有以下使用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)
}
I am able to show the Score in ScoreTableViewController thru: 我可以通过以下方式在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
}
However, when I restart the app, the DATA IS NO LONGER THERE. 但是,当我重新启动应用程序时,数据就不再存在了。
I have seen this code to save the “totalScore” data: 我看过以下代码来保存“ 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")
}
}
However, how do I SAVE ALL of the data that I need? 但是,如何保存所需的所有数据? (For instance: datePlayed, totalScore, totalAnswered, totalDuration, and gameStatus)
(例如:datePlayed,totalScore,totalAnswered,totalDuration和gameStatus)
The easiest way is to do something like this after you have populated the gameResult
object with everything you wanted to save. 最简单的方法是在将要保存的所有内容填充到
gameResult
对象之后,执行类似的gameResult
。
do {
try appDelegate.managedObjectContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}
You need to call save on the appropriate managedObjectContext in order for the object to be stored. 您需要在适当的managedObjectContext上调用save以便存储对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.